mobx autorun code example

Example 1: mobx listen to changes

import { observable, observe } from "mobx"

const person = observable({
    firstName: "Maarten",
    lastName: "Luther"
})

const disposer = observe(person, change => {
    console.log(change.type, change.name, "from", change.oldValue, "to", change.object[change.name])
})

person.firstName = "Martin"
// Prints: 'update firstName from Maarten to Martin'

disposer()
// Ignore any future updates

// observe a single field
const disposer2 = observe(person, "lastName", change => {
    console.log("LastName changed to ", change.newValue)
})

Example 2: mobx listen to changes

const theme = observable({
    backgroundColor: "#ffffff"
})

const disposer = intercept(theme, "backgroundColor", change => {
    if (!change.newValue) {
        // ignore attempts to unset the background color
        return null
    }
    if (change.newValue.length === 6) {
        // correct missing '#' prefix
        change.newValue = "#" + change.newValue
        return change
    }
    if (change.newValue.length === 7) {
        // this must be a properly formatted color code!
        return change
    }
    if (change.newValue.length > 10) disposer() // stop intercepting future changes
    throw new Error("This doesn't like a color at all: " + change.newValue)
})