Lifecycle Hooks
All of the below hooks can be created by returning an action with the given name, like:
const Todo = types
.model("Todo", { done: true })
.actions(self => ({
afterCreate() {
console.log("Created a new todo!")
}
}))
The exception to this rule is the preProcessSnapshot
hook. Because it is needed before instantiating the model elements, it needs to be defined on the type itself:
types
.model("Todo", { done: true })
.preProcessSnapshot(snapshot => ({
// auto convert strings to booleans as part of preprocessing
done: snapshot.done === "true" ? true : snapshot.done === "false" ? false : snapshot.done
}))
.actions(self => ({
afterCreate() {
console.log("Created a new todo!")
}
}))
Hook | Description |
---|---|
preProcessSnapshot |
Called before creating an instance or applying a snapshot to an existing instance, this hook is called to give the option to transform the snapshot before it is applied. The hook should be a pure function that returns a new snapshot. This can be useful to do some data conversion, enrichment, property renames, etc. This hook is not called for individual property updates. (Note: Unlike the other hooks, this one is not created as part of the actions initializer, but directly on the type.) (Note: The transformation must be pure; it should not modify its original input argument.) |
afterCreate |
Called immediately after an instance is created and initial values are applied. Children will fire this event before parents. |
afterAttach |
Called as soon as the direct parent is assigned. (This node is attacked to another node.) |
postProcessSnapshot |
Called every time a new snapshot is being generated. Typically, it is the inverse function of preProcessSnapshot . This function should be a pure function that returns a new snapshot. |
beforeDetach |
Called as soon as the node is removed from the direct parent, but only if the node is not destroyed. In other words, when detach(node) is used. |
beforeDestroy |
Called before the node is destroyed, as a result of calling destroy , or by removing or replacing the node from the tree. Child destructors will fire before parents. |
All hooks can be defined multiple times and can be composed automatically.