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
The whole point for removing data from model is call 'destroy', sometime you might need 'getParent' if the data you want to remove is not in current tree node.
import { types, getParent, destroy } from "mobx-state-tree" export const WishListItem = types .model({ name: types.string, price: types.number, image: "" }) .actions(self => ({ changeName(newName) { self.name = newName }, changePrice(newPrice) { self.price = newPrice }, changeImage(newImage) { self.image = newImage }, remove() { getParent(self, 2).remove(self) } })) export const WishList = types .model({ items: types.optional(types.array(WishListItem), []) }) .actions(self => ({ add(item) { self.items.push(item) }, remove(item) { destroy(item) } })) .views(self => ({ get totalPrice() { return self.items.reduce((sum, entry) => sum + entry.price, 0) } }))