Listening to observables, snapshots, patches, or actions

MST is powered by MobX. This means that it is immediately compatible with observer components, or reactions like autorun:

import { autorun } from "mobx"

autorun(() => {
    console.log(storeInstance.selectedTodo.title)
})

But, because MST keeps immutable snapshots in the background, it is also possible to be notified when a new snapshot of the tree is available. This is similar to .subscribe on a redux store:

onSnapshot(storeInstance, newSnapshot => {
    console.dir("Got new state: ", newSnapshot)
})

However, sometimes it is more useful to precisely know what has changed, rather than just receiving a complete new snapshot. For that, MST supports JSON-patches out of the box.

onPatch(storeInstance, patch => {
    console.dir("Got change: ", patch)
})

storeInstance.todos[0].setTitle("Add milk")
// prints:
{
    path: "/todos/0",
    op: "replace",
    value: "Add milk"
}

Similarly, you can be notified whenever an action is invoked by using onAction:

onAction(storeInstance, call => {
    console.dir("Action was called: ", call)
})

storeInstance.todos[0].setTitle("Add milk")
// prints:
{
    path: "/todos/0",
    name: "setTitle",
    args: ["Add milk"]
}

It is even possible to intercept actions before they are applied by adding middleware using addMiddleware:

addMiddleware(storeInstance, (call, next) => {
    call.args[0] = call.args[0].replace(/tea/gi, "Coffee")
    return next(call)
})

Finally, it is not only possible to be notified about snapshots, patches, or actions; it is also possible to re-apply them by using applySnapshot, applyPatch, or applyAction!

results matching ""

    No results matching ""