redux-action-reducer
Remove redux reducer boilerplate
Your actions need to comply with FSA (Flux Standard Action).
npm i --save-dev redux-action-reducer
createReducer(...actionHandlers)(defaultValue)
actionHandler: String | Array
An actionHandler
is an action type (String) or a list of action types (Array) with an optional action reducer at the end. By default, an action reducer returns its payload: (state, payload, error) => payload
.
// [ 'ACTION1', (state, payload) => payload ]'ACTION' // [ 'ACTION1', 'ACTION2', (state, payload) => payload ] 'ACTION1' 'ACTION2' 'ACTION1' ...state payloadid: payload
whenError and whenSuccess
whenError
and whenSuccess
are shorthand methods to avoid having to differentiate between error and success in action reducers.
whenError
will only apply to actions with error: true
, the current state
will be returned if an action is not an error. successReducer
works the
other way round.
whenError
and whenSuccess
both accept a reducer function (state, payload) => /*...*/
.
; const list = ; // Instead ofconst list = );
If a reducer is not supplied, payload
will be returned.
extendReducer(reducer)(...actionHandlers)(defaultValue)
Re-use an existing reducer and extend it with extra handlers using this pattern, for example:
const reducer = 'ACTION1' ...state payloadid: payload const reducer2 =
This comes in handy when a common pattern for a reducer can be re-used throughout the application, but sometimes requires extra cases handling.
Reducer Factories
What are reducer factories?
In an application it is common for patterns to become reused many times over, in these cases some form of abstraction is useful. This library can be used to define a reducer factory that can be re-used throughout the code-base, here is an example.
// queryReducerFactory.js {}
This factory will create a reducer that can be combined wherever is useful in the state tree (using redux combineReducers), and is generated by passing in an object with 3 arrays of actions to perform the functions, setAll, setField and resetAll.
This factory could be implemented as follows:
const reducer =
This gives full flexibility when defining which actions will be allowed to trigger the reducer behaviour.
Extra cases can be handled in specific instantiations by using the extendReducer
pattern (Above)
Examples
Full example
We can search a list of items, add or remove them from a list and empty that list.
;;; const search = ''; const selectedItems = ''; search selectedItems;
Single action reducer, primitive value
{ }
becomes:
; const search = 'info';
Multiple action reducer, primitive value
{ }
becomes:
const search = '';
Multiple-action reducer, array
{ }
becomes:
const selectedItems = '';