Save 45% for a limited time.

Get access to all courses and lessons on egghead today.

Autoplay

    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
    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 We're still missing some features. Let's make sure we also have a button to remove the current item.

    00:07 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.

    00:31 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.

    00:42 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.

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

    01:09 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."

    01:21 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.

    01:49 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.

    02:16 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.

    Discuss

    Discuss