I am getting to know the reducer composition concept in Redux, and I was confused about how the initial state should be set in the sub-reducers.
A similar question was this but it concerns only the top-level reducers for each part of the state tree.
As I understand it, each reducer should be supplying initial state for the part of the state tree it's responsible for.
For example, if I had a state tree like this:
{
dashboard:{
stats:{
sales:23,
purchases:22
},
messages:{
unread:3,
draft:5
},
//...etc
},
//...
}
And I had one top level reducer for dashboard, as well as reducers for stats
and messages
, should the initial state for the parts of the dashboard be set in the dashboard reducer, or in the reducers for each part, and if so, how would this code look like?
My initial thought was to implement the dashboard reducer like this:
const initialState = {
stats: {},
messages: {},
//...
}
export default function dashboard(state = initialState, action) {
switch (action.type) {
case FETCH_STATS:
case FETCH_STATS_SUCCESS:
case FETCH_STATS_FAILURE:
return {
...state,
stats: stats(state.stats, action)
}
case FETCH_MESSAGES:
case FETCH_MESSAGES_SUCCESS:
case FETCH_MESSAGES_FAILURE:
return {
...state,
messages: messages(state.messages, action)
}
//...any other action cases
default:
const combined = combineReducers({
stats,
messages
})
return {
...state, //for any part without a reducer
...combined
}
}
}
Is my reasoning correct? Any improvement suggestions are also welcome.