MobX

Basics

Creating stores

import { action, makeObservable, observable } from 'mobx'

class TodoStore {
    todos = []

    constructor() {
        makeObservable(this, {
            todos: observable,
            addTodo: action
        })
        /* or makeAutoObservable(this) */
    }

    get incompleteTodos() {
        return this.todos.filter(t => !t.complete)
    }

    addTodo(name) {
        this.todos.push({ name, complete: false })
    }
}
export default new TodoStore()
import { observer } from 'mobx-react-lite'

export default observer(function TodoList() {
    /* ... */
}
class RootStore {
    constructor() {
        this.userStore = new UserStore(this)
        this.todoStore = new TodoStore(this)
    }
}

class UserStore {
    constructor(rootStore) {
        this.rootStore = rootStore
    }

    getTodos(user) {
        // Access todoStore through the root store.
        return this.rootStore.todoStore.todos.filter(todo => todo.author === user)
    }
}

class TodoStore {
    todos = []
    rootStore

    constructor(rootStore) {
        makeAutoObservable(this)
        this.rootStore = rootStore
    }
}

Persistent stores