Views

Any fact that can be derived from your state is called a view or derivation. Views come in two flavors: (1) views with arguments, (2) views without arguments. The latter are called computed values, based on the computed concept in mobx. The main difference between the two is that computed properties create an explicit caching point, but further they work the same as any other computed value or MobX-based reaction like @observer components can react to them. Computed values are defined using getter functions.

import { autorun } from "mobx"

const UserStore = types
    .model({
        users: types.array(User)
    })
    .views(self => ({
        get amountOfChildren() {
            return users.filter(user => user.age < 18).length
        },
        amountOfPeopleOlderThan(age) {
            return users.filter(user => user.age > age).length
        }
    }))

const userStore = UserStore.create(/* */)

// Every time the userStore is updated in a relevant way, log messages will be printed
autorun(() => {
    console.log("There are now ", userStore.amountOfChildren, " children"
})
autorun(() => {
    console.log("There are now ", userStore.amountOfPeopleOlderThan(75), " pretty old people"
})

If you want to share volatile state between views and actions, use .extend instead of .views + .actions.

results matching ""

    No results matching ""