-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path06_reducer_composition_w_objects.js
103 lines (85 loc) · 1.92 KB
/
06_reducer_composition_w_objects.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
// http://jsbin.com/xoganemojo/11/edit?js,console
const todo = (state, action) => {
switch (action.type) {
case 'ADD_TODO':
return {
id: action.id,
text: action.text,
completed: false
};
case 'TOGGLE_TODO':
if (state.id !== action.id) {
return state;
}
return {
...state,
completed: !state.completed
};
default:
return state;
}
};
const todos = (state = [], action) => {
switch (action.type) {
case 'ADD_TODO':
return [
...state,
todo(undefined, action)
];
case 'TOGGLE_TODO':
return state.map((t) => todo(t, action));
default:
return state;
}
};
const visibilityFilter = (state = 'SHOW_ALL', action) => {
switch (action.type) {
case 'SET_VISIBILITY_FILTER':
return action.filter;
default:
return state;
}
};
/** TESTS ARE REMOVED, COPY PASTE AND TEST! **/
// To change our state from array to object, we dont have to
// remove our previous reducers, we just going to create
// wrapper reducer for our app.
// And we going to use it when we are creating store (instead of todos, we'll use todoApp)
// We'll do it with reselect in future.
const todoApp = (state = {}, action) => {
return {
todos: todos(
state.todos,
action
),
visibilityFilter: visibilityFilter(
state.visibilityFilter,
action
)
}
}
const { createStore } = Redux;
const store = createStore(todoApp);
console.log('initialState: ', store.getState());
store.dispatch({
type: 'ADD_TODO',
id: 0,
text: 'Learn Redux'
});
console.log(store.getState());
store.dispatch({
type: 'ADD_TODO',
id: 1,
text: 'Go Shopping'
});
console.log(store.getState());
store.dispatch({
type: 'TOGGLE_TODO',
id: 1
});
console.log(store.getState());
store.dispatch({
type: 'SET_VISIBILITY_FILTER',
filter: 'SHOW_COMPLETED'
});
console.log(store.getState());