Proposal: mechanism for handling multiple actions with the same reducer.
See original GitHub issueHi all!
I’d like to propose a new feature to allow handling multiple actions with the same reducer in the case that someone has very general, over-arching properties of their state.
For example, when using redux on its own I’ve found it useful to have a loading
property which gets reduced like this:
function loading(state = false, action) {
switch(action.type) {
case LOAD_SOMETHING_START:
case LOAD_SOMETHING_ELSE_START:
return true;
case LOAD_SOMETHING_COMPLETE:
case LOAD_SOMETHING_ELSE_COMPLETE:
return false;
default:
return state;
}
}
I find this preferable to invoking an action to update loading
within a composite/async action using redux-thunk because I would prefer not to have my state’s other properties know about the loading
property and keep that logic central to the reducer for loading
.
Initially I’d like to propose being able to define an action handler with a name that contains a delimiter like |
. To illustrate with the previous example:
handleActions({
'LOAD_SOMETHING_START | LOAD_SOMETHING_ELSE_START': () => true,
'LOAD_SOMETHING_COMPLETE | LOAD_SOMETHING_ELSE_COMPLETE': () => false
}, false);
Alternatively, if it would be preferable not to expose the details about how to delimit action names, a function combineActions()
might help:
const startActions = combineActions('LOAD_SOMETHING_START', 'LOAD_SOMETHING_ELSE_START');
const completeActions = combineActions('LOAD_SOMETHING_COMPLETE', 'LOAD_SOMETHING_ELSE_COMPLETE');
handleActions({
[startActions]: () => true,
[completeActions]: () => false
}, false);
What do you think? I’d be thrilled to submit a PR for this if we agree it would be worthwhile.
Issue Analytics
- State:
- Created 8 years ago
- Reactions:9
- Comments:8
Top GitHub Comments
I’ve been using this feature at work via a fork of this project and it’s turned out great for DRY’ing up our reducers (especially when using reducer composition). I’ll see if I can contribute this feature back to the repository.
As mentioned above though, I don’t see a cleaner path to doing this than the
combineActions
approach.I was thinking that a conventional delimiter like
|
could work, but there’s no obvious way for library users to join action creators (which can be used as inputs tohandleActions
orhandleAction
) since the way an action creator stores its type (viatoString
) seems encapsulated from the library user.So, I think the
combineActions
approach seems the most reasonable.