type-to-reducer
This module provides a function typeToReducer
, which accepts an object (reducerMap
) and returns a reducer function composing other reducer functions described by the reducerMap
.
Why?
This is pretty much the same as the handleActions
function you can find in https://github.com/acdlite/redux-actions. The differences being, type-to-reducer
only exposes the function as a default, and allows nesting of the reducerMap
object.
Usage
npm install type-to-reducer --save
The reducerMap
you supply to the function will have keys that correspond to dispatched action types and the values for those keys will be reducer functions. When the returned reducer function is called with state and an action object, the action's type will be matched against the previously provided reducerMap
keys, if a match is found, the key's value (the reducer function) will be invoked with the store's state and the action.
Also, you can describe an initial state with the second argument to typeToReducer
.
Oh and you can also set reducerMap
s as the values too, these objects will be nested instances of the same shaped object you supplied to typeToReducer
.
If that sounded a bit complicated, the example below should make it clearer. NB, it helps if you're familiar with redux.
const initialState = data: null isPending: false error: false // supply the reducerMap objectconst myReducer =
Then the myReducer
would be used like so:
let state = foo: 'bar' let newState = // newState will deep equal { foo: 'bar', data: `an action's payload.` }
Group reducers by a prefix when objects are nested.
const initialState = data: null isPending: false error: false const myReducer = // usagelet previousState = Whatever; let newState = // newState shallow deeply equals { isPending: true }
Custom Type Delimiter
You can add a custom type delimiter instead of the default '_'
.
This will set it for every reducer you create after the custom delimiter is set, yes a dirty stateful function. This is for convenience so you can set it for your whole project up front and not to pollute the main function abstraction for rare settings.
const initialState = data: null isPending: false const myReducer = // Then use the delimiter in your action type