mangocaptain mangocaptain - 3 months ago 14
React JSX Question

React redux logic done in parent reducer vs. child reducer

In the react redux doc todo example, Dan passes the action with type

TOGGLE_TODO
to the
todos
which then passes it on to each individual todo. I notice that his logic was checking for the
todo.id
was in the
todo
reducer. Couldn't this logic have been done in the
todos
as well? To me, it would seem better to take care of the logic at a higher level as your iterating through each todo rather than passing the work to every todo and having them figure out if they need to toggle or now. Is there a reason why Dan did it this way?

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 Object.assign({}, 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
}
}

export default todos

Answer

I think you are right, if you take a look at todomvc example from redux source code repository, you'll see only one todos reducer.

The docs may be a bit outdated or such nested reducers may be just an example of its possibilities.

Comments