1.0.1 • Published 8 years ago

redux-strategic-reducer v1.0.1

Weekly downloads
3
License
ISC
Repository
github
Last release
8 years ago

strategicReducer

Strategy pattern for Redux reducers

Redux is a godsend. But, you may have noticed that all the Redux Docs use JavaScript's not-so-useful switch/case construct. If you prefer re-usable, composable, function-based reducers, redux-strategic-reducer offers a better way.

Installation

To install the stable version:

npm install --save redux-create-reducer

Usage

strategicReducer

Create a strategy-based reducer thus:

import { strategicReducer } from 'redux-create-reducer';

const defaultState = { title: null };

export default const counter = strategicReducer(defaultState, {
  'SET_TITLE': (state, action) =>
    Object.assign({}, state, { title: action.payload })
,
  'CLEAR_TITLE': (state, action) =>
    Object.assign({}, state, { title: null })
});

as opposed to the switch-based version

export default function counter(state = 0, action) {
  switch (action.type) {

  case 'SET_TITLE':
    return Object.assign({}, state, { title: action.payload })

  case 'CLEAR_TITLE':
    return Object.assign({}, state, { title: null })

  default:
    return state
  }
}

setProperty and clearProperty

There are helper functions that will create setters and clearers for you, given a property name:

import {
  strategicReducer,
  setProperty,
  clearProperty,
} from 'redux-create-reducer';

const defaultState = { title: null };

export default const counter = strategicReducer(defaultState, {
  'SET_TITLE': setProperty('title')
,
  'CLEAR_TITLE': clearProperty('title')});

That should produce a strategic reducer equivalent to the example in the section above.