[Proposal] Make combineReducers
pass extra arguments to child reducers
#1904
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This can be useful a couple cases:
1. Reducers with dependencies
In my opinion the most explicit and convenient way to have one branch of reducers dependent on another branch is to make them have common parent that calculates dependency branch first and then passes its to the dependent reducer:
The change in this PR allows
dependentReducer
to be built from smaller parts, each one accepting dependency.2. Multiple branches of same shape
Suppose we are developing an instant messenger. We can switch between chat views for different contacts and we want to store some data for each view, e.g. entered text, scroll position etc.
Let's structure state like this:
Actions:
My first approach to this was to have parent reducer look into action's
contact
prop and pass action tochatViewReducer
for particular branch. But that couples parent to child, parent has to know of all actions that child accepts etc.So my current approach is to pass all actions to
chatViewReducer
for all child branches withcontact
passed as third argument:Once again, this change allows
chatViewReducers
to be built from smaller parts each acceptingcontact
as third argument, allowing them to filter incoming actions bycontact
to see if they correspond to that particular chat view.Right now I have a custom
combineReducers
version that is almost the same as original.Also, the above pattern can be generalised as reducer factory: