redux-merge-reducers
A decorator to make your Redux's reducers mergeable.
For what?
In the development of reusable Container components, I noticed the importance of shared reducers. Because these are often combined with the different host applications, I can't handle application specific actions in it. The shared reducers should handle only shared actions.
My solution: Merge, not Combine
combineReducers
function always join them horizontally, so it can't be used for my purpose.
I needed to chain reducers and make a single reducer.
reduce-reducers
Difference fromreduce-reducers doesn't consider the initial state of additional reducers.
Installation
npm install --save redux-merge-reducers
Usage
- Make shared reducers mergeable
- Merge with the extra reducer
- That's it
⚡
mergeable()
function.
1. Wrap your reducer with import mergeable from 'redux-merge-reducers';
function sharedReducer(state = { ... }, action) {
// ...
}
export default mergeable(sharedReducer);
merge()
method with the extra reducer.
2. Call import sharedReducer from '...';
function extraReducer(state = {...}, action) {
// ...
}
export default combineReducers({
foo, bar, sharedreducer: sharedReducer.merge(extraReducer)
});
Tips
Use original reducer (without merging)
If you want to use shared reducers without customization, you can put mergeable reducers without calling merge()
method.
import sharedReducer from '...'; // this reducer is decorated
export default combineReducers({
foo, bar, sharedReducer // without merging
});
Merge initial state
The initial state given by the extra reducer should be merged with the shared one.
function sharedReducer(state = { a: 0, b: true }, action) {
// ...
}
function extraReducer(state = { b: false, c: 'hello' }, action) {
// ...
}
// => { a: 0, b: false, c: 'hello' }
Be careful that the extra reducer's initial state has a priority over the shared one.
Caveat
The extra reducer will be called before the original. The shared reducer takes the new state which is produced by the extra.
API
redux-merge-reducers exports one function.
mergeable(reducer)
reducer
(function) [required] : a reducer function you want to make it mergeable.
License
MIT
Author
Yuki Kodama / @kuy