12 Days of Baddass Courses sale! Get instant access to the entire egghead library of courses and lessons for 58% off.

Runs out in:
13 : 08 : 52 : 25
Become a member
to unlock all features

    Remove Model Instances from the Tree

    Michel WeststrateMichel Weststrate

    In this lesson we will dive a bit more into the tree semantics of MST.

    In this lesson you will learn:

    • Actions can only modify their own subtree
    • The use of getParent to find the parent of a model instance
    • Using destroy to remove an instance entirely from the tree


    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




    Instructor: We're still missing some features. Let's make sure we also have a button to remove the current item.

    Besides the editor, we also have a remove button. To onClick is actually pretty simple because that can be directly defined as action on the item. Because item doesn't have any binding issues with this, we can just simply pass the remove action of the item to the onClick handler of this button.

    Of course, it doesn't work yet because we didn't define the remove action. Let's go back to our model and introduce the remove action.

    The interesting thing about the action is that they can only modify the object they belong to or any of their children. Removing a wish-list item is actually not a modification of the wish list itself. It's a modification of the collection it belongs to.

    What we are going to do is that we simply delegate this remove method to the owner of this wish-list item.

    To find the owner in this wish-list utility, it's called, "Get parent." What we're going to do is, on the parent, we will call, "Remove myself."

    Now, this two means that if you...I mentioned this wish list being a tree. The two means that we want to go two parents up, so it's basically the same as, "Get parent of get parent." We need to be two up, because one up, then we add some to the items' array. We actually want to invoke a method where we are now going to introduce on the wish list itself.

    We can simply splash the array with index we are currently looking at, and remove one. This will drop the item from the list just like that, but we can actually express this more simple by using, again, a generic utility called destroy. Destroy just removes an item from the container it lives in.

    Because a mobx-state-tree is always a tree, every item list lives at one unique location. You can simply destroy and make sure that it's removed from the parents.