-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstore.js
68 lines (62 loc) · 1.38 KB
/
store.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import { types, applySnapshot, destroy } from "mobx-state-tree";
import makeInspectable from "mobx-devtools-mst";
import * as uuid from "uuid";
let store = null;
const Todo = types
.model("Todo", {
id: types.identifier,
text: types.string,
completed: false
})
.actions(self => ({
toggleCompleted() {
self.completed = !self.completed;
}
}));
const Store = types
.model({
todos: types.array(Todo)
})
.views(self => {
return {
get unfinishedTodos() {
return self.todos.filter(t => !t.completed);
},
findById(id) {
const found = self.todos.find(t => t.id === id);
if (!found) {
throw new Error(`Error. No todo found with id: ${id}`);
}
return found;
}
};
})
.actions(self => ({
addTodo(todoText) {
self.todos.push({
id: uuid.v4(),
text: todoText
});
},
deleteTodo(id) {
destroy(self.findById(id));
},
toggleCompleted(id) {
self.findById(id).toggleCompleted();
}
}));
export function initStore(isServer, snapshot = null) {
if (isServer) {
store = Store.create({ todos: [] });
}
if (store === null) {
store = Store.create({ todos: [] });
if (process.env.NODE_ENV === "development") {
makeInspectable(store);
}
}
if (snapshot) {
applySnapshot(store, snapshot);
}
return store;
}