Just started exploring Redux and curious about the best way to implement multiple reducers. Specifically, I'm interested in how to direct actions to a specific reducer.
For example, if I have two reducers: one for users and one for posts.
User Reducer
export function userReducer(state: User, action: Action) {
switch (action.type) {
case SOME_ACTION:
return state;
default:
return state || new User();
}
}
Post Reducer
export function postReducer(state: Post, action: Action) {
switch (action.type) {
case SOME_OTHER_ACTION:
return state;
default:
return state || new Post();
}
}
Initialization
StoreModule.provideStore({user: userReducer, post: postReducer}),
I would like to be able to target a specific reducer like this:
const store = this._store.select<User>('user');
store.dispatch({type: SOME_ACTION, payload: {blah: 'blah'}})
and have only the userReducer respond.
Currently, when I dispatch an action, both userReducer
and postReducer
are triggered. Is this the standard behavior in Redux?
If not, is there a more efficient way to achieve this? It seems inefficient for all reducers to update on every dispatch.
Update
This question is prompted by the following section:
default:
return state || new User();
It doesn't seem ideal to check for null state in the default case. I would prefer to do this instead:
default:
return new User();
Currently, I am unable to implement this because if I dispatch SOME_ACTION
, both postReducer.default
and userReducer.SOME_ACTION
are executed.
Furthermore, I can foresee potential debugging challenges if I mistakenly use the same string for actions in multiple reducers, resulting in both being triggered.