with mobx
The Problem
Mobx Core concepts
Demo App
Redux vs Mobx
Manage/Provide state across large and complex component tree
Global state container/manger
---- with flavors ----
immutable mutable
passive reactive
dispatcher pure function
Anything that can be derived from the application state, should be derived. Automatically.
import { observable } from "mobx"
class Todo {
id = Math.random();
@observable title = "";
@observable finished = false;
}import { decorate, observable } from "mobx"
class Todo {
id = Math.random();
title = "";
finished = false;
}
decorate(Todo, {
title: observable,
finished: observable
})class TodoList {
@observable todos = [];
@computed get unfinishedTodoCount() {
return this.todos.filter(todo => !todo.finished).length;
}
}autorun(() => {
console.log("Tasks left: " + todos.unfinishedTodoCount)
})
class MyResource {
constructor() {
when(
// once...
() => !this.isVisible,
// ... then
() => this.dispose()
);
}
@computed get isVisible() {
// indicate whether this item is visible
}
dispose() {
// dispose
}
}import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import {observer} from 'mobx-react';
@observer
class TodoListView extends Component {
render() {
return <div>
<ul>
{this.props.todoList.todos.map(todo =>
<TodoView todo={todo} key={todo.id} />
)}
</ul>
Tasks left: {this.props.todoList.unfinishedTodoCount}
</div>
}
}
const TodoView = observer(({todo}) =>
<li>
<input
type="checkbox"
checked={todo.finished}
onClick={() => todo.finished = !todo.finished}
/>{todo.title}
</li>
)
const store = new TodoList();
ReactDOM.render(<TodoListView todoList={store} />, document.getElementById('mount'));class TodoStore {
@observable todos = []
@action addTodo = (title) => {
this.todos.push(new Todo(title));
}
@action removeTodo = (id) => {
this.todos.splice(this.todos.findIndex(todo => todo.id === id),1);
}
@action updateTodo = (id,newValue) => {
this.todos.find(todo => todo.id === id).title = newValue;
}
}Multiple Stores
Reactive
Observable data structures
Nested state
Mutable
Automatically (tu)
Read/Write state
Impure
Optional Actions
Single Store
Passive
Plain Objects
Normalized state
Immutable
Manually (tu)
Read only state
Pure
Requires Actions