-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReduxExample.js
130 lines (108 loc) · 2.32 KB
/
ReduxExample.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
// library code
function createStore(reducer) {
// Store should have parts
// The state
// Get the state
// Listen to changes on state
// Update the state
let state
let listeners = []
const getState = () => state
const subscribe = (listener) => {
listeners.push(listener)
return () => {
listeners = listeners.filter(l => l != listener)
}
}
const dispatch = (action) => {
state = reducer(state, action);
listeners.forEach(listener => listener())
}
return {
getState,
subscribe,
dispatch
}
}
function todos(state = [], action) {
switch (action.type) {
case 'ADD_TODO':
return state.concat([action.todo])
case 'REMOVE_TODO':
return state.filter(todo => todo.id != action.id)
case 'TOGGLE_TODO':
return state.map(todo => todo.id != action.id ? todo : Object.assign({}, todo, {
complete: !todo.complete
}))
default:
return state
}
}
function goals(state = [], action) {
switch (action.type) {
case 'ADD_GOAL':
return state.concat([action.goal])
case 'REMOVE_GOAL':
return state.filter((goal) => goal.id !== action.id)
default:
return state
}
}
function app(state = {}, action) {
return {
todos: todos(state.todos, action),
goals: goals(state.goals, action),
}
}
const store = createStore(app)
store.subscribe(() => console.log("State is", store.getState()));
store.dispatch({
type: 'ADD_TODO',
todo: {
id: 0,
name: 'Master React',
complete: false,
}
})
store.dispatch({
type: 'ADD_TODO',
todo: {
id: 1,
name: 'Learn Redux',
complete: false,
}
})
store.dispatch({
type: 'ADD_TODO',
todo: {
id: 2,
name: 'Go to the gym',
complete: true,
}
})
store.dispatch({
type: 'REMOVE_TODO',
id: 1
})
store.dispatch({
type: 'TOGGLE_TODO',
id: 0
})
store.dispatch({
type: 'ADD_GOAL',
goal: {
id: 0,
name: 'Learn Redux'
}
})
store.dispatch({
type: 'ADD_GOAL',
goal: {
id: 1,
name: 'Lose weight'
}
})
store.dispatch({
type: 'REMOVE_GOAL',
id: 1
})