All Projects → kuy → redux-merge-reducers

kuy / redux-merge-reducers

Licence: other
A decorator to make your Redux's reducers mergeable.

Programming Languages

javascript
184084 projects - #8 most used programming language

NPM Package Travis Dependency Status Greenkeeper badge

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.

Difference from reduce-reducers

reduce-reducers doesn't consider the initial state of additional reducers.

Installation

npm install --save redux-merge-reducers

Usage

  1. Make shared reducers mergeable
  2. Merge with the extra reducer
  3. That's it

1. Wrap your reducer with mergeable() function.

import mergeable from 'redux-merge-reducers';

function sharedReducer(state = { ... }, action) {
  // ...
}

export default mergeable(sharedReducer);

2. Call merge() method with the extra reducer.

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

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].