Save 45% for a limited time.

Get access to all courses and lessons on egghead today.

Autoplay

    Create an Entry Form to Add Models to the State Tree

    Michel WeststrateMichel Weststrate

    It is time to add new entries to the wishlist. We will achieve this by reusing forms and models we've built so far.

    In this lesson you will learn:

    • MST is not limited to a single state tree. Every model can form a tree on its own
    • Appending model instances to the state tree
    reactReact
    ^16.0.0
    mobxMobX
    ^3.0.0
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    Instructor: 00:00 Now there's one thing left to do. Actually, the most important feature is to be able to add new items to our wish list. To do so, I'm going to introduce yet another component, the wish list item entry. This component is, of course, very similar to the edit component, so we're going to reuse that one.

    00:24 First we're going to import all the typical React and mobx stuff we're in the mean time familiar with, that we're going to import our edit component, as well, because we're going to wrap that one. In this wish list component, I'm going to leverage a feature from mobx-state-tree, and that feature is that basically any model can be an independent tree of its own.

    00:50 So far in this application we have, has only one state tree, and that is the list, which lives at the root of the application. Now, in this component, I'm going to create an item that lives stand-alone, which is not part of a wish list. This is the item this component is going to edit. It's an entry without name yet, and also the price is zero.

    01:20 The rendering of these components is, of course, pretty straightforward, because we can just reuse what we already created earlier. I put a wish list item add component here, and, as item, we pass it the entry which only lives inside this component, and we introduce a small add button. That is pretty straightforward so far.

    01:45 We leverage the item edit component, and we just pass it an empty wish list item of our own. When we then press on add, we can simply repeat a trick we did earlier. We can say, "Hey, that wish list, we should be passing it to these components."

    02:03 To that one, we add the current entry, and then we change the states and simply repeat this. Of course, you can extract this to a utility function, but you get the gist of it.

    02:16 The only thing left to do is to actually call this component, which is now pretty simple. We import in our list view and we pass the wish list to it, so it has the correct list to add it to.

    02:33 Now we can just add items.

    Discuss

    Discuss