Computed Values
With MobX, you can define values that will be derived automatically when relevant data is modified. By using the @computed
decorator or by using getter / setter functions when using (extend)Observable
.
class TodoList {
@observable todos = [];
@computed get unfinishedTodoCount() {
return this.todos.filter(todo => !todo.finished).length;
}
}
MobX will ensure that unfinishedTodoCount
is updated automatically when a todo is added or when one of the finished
properties is modified. Computations like these resemble formulas in spreadsheet programs like MS Excel. They update automatically and only when required.