Skip to content

Commit 90ef233

Browse files
committed
Add missing reducer composition example to docs
The code for the first implementation of `todos` as an example of reducer composition is actually the same as the previous example, causing the following paragraph ("This is called *reducer composition*, and it’s the fundamental pattern of building Redux apps") to make no sense. This change adds the `todos` function from the following example to make this one more clear. There are other ways the composition could be done, certainly, and I'm not sure that the one I chose is the most iconic, so feel free to suggest alternatives. :-)
1 parent de2d11d commit 90ef233

File tree

1 file changed

+27
-18
lines changed

1 file changed

+27
-18
lines changed

docs/basics/Reducers.md

Lines changed: 27 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -199,32 +199,41 @@ function todoApp(state = initialState, action) {
199199
Is there a way to make it easier to comprehend? It seems like `todos` and `visibilityFilter` are updated completely independently. Sometimes state fields depend on one another and more consideration is required, but in our case we can easily split updating `todos` into a separate function:
200200

201201
```js
202+
function todos(state = [], action) {
203+
switch (action.type) {
204+
case ADD_TODO:
205+
return [
206+
...state,
207+
{
208+
text: action.text,
209+
completed: false
210+
}
211+
]
212+
case COMPLETE_TODO:
213+
return [
214+
...state.slice(0, action.index),
215+
Object.assign({}, state[action.index], {
216+
completed: true
217+
}),
218+
...state.slice(action.index + 1)
219+
]
220+
default:
221+
return state
222+
}
223+
}
224+
202225
function todoApp(state = initialState, action) {
203226
switch (action.type) {
204227
case SET_VISIBILITY_FILTER:
205228
return Object.assign({}, state, {
206229
visibilityFilter: action.filter
207230
})
208231
case ADD_TODO:
209-
return Object.assign({}, state, {
210-
todos: [
211-
...state.todos,
212-
{
213-
text: action.text,
214-
completed: false
215-
}
216-
]
217-
})
218232
case COMPLETE_TODO:
219-
return Object.assign({}, state, {
220-
todos: [
221-
...state.todos.slice(0, action.index),
222-
Object.assign({}, state.todos[action.index], {
223-
completed: true
224-
}),
225-
...state.todos.slice(action.index + 1)
226-
]
227-
})
233+
return {
234+
...state,
235+
todos: todos(state.todos, action)
236+
};
228237
default:
229238
return state
230239
}

0 commit comments

Comments
 (0)