Eric Allen
Interweb Alchemist
State Management You Should Check Out
A not-quite Lightning Talk
import { createStore } from 'satcheljs';
// this creates a Symbol that will be returned
// when you call this method again
export default createStore(
'todoStore',
{ todos: [] },
);
import { action } from 'satcheljs';
export default action(
'ADD_TODO',
(text: string) => ({ text: text }),
);
import { mutator } from 'satcheljs';
import todoStore form '../store';
import { ADD_TODO } from '../actions';
export default mutator(ADD_TODO, (actionMessage) => {
const store = todoStore();
store.todos.push({
id: Math.random(),
text: actionMessage.text,
});
};
import { action, orchestrator, dispatch } from 'satcheljs';
import { RECEIVE_TODOS, ADD_TODO } from '../actions';
export default orchestrator(RECEIVE_TODOS, async () => {
// let's grab any todos our user has saved on our server
await fetch(process.env.TODO_SERVER)
.then(response => response.json())
.then(data => {
data.forEach(todo => dispatch(ADD_TODO, todo)
})
;
};
import React, { Component } from 'react';
import { observer } from 'mobx-react';
import todoStore from '../store';
const mapTodos = todos => todos.map(todo => <li>{todo.text}</li>);
@observer
// if you're gonna use decorators, you have to use a Class
// instead of a just a functional Component
export default class TodoListComponent extends Component {
private store = todoStore();
render() {
const { todos } = this.store;
return (
<ol>
{mapTodos(todos)}
</ol>
);
}
}
By Eric Allen