Utils that keeps the redux reducers clean, yet still powerful.
npm i redux-reducers-strategy
import makeReducerHandler from 'redux-reducers-strategy'
const initialState = {
data: [],
loading: false,
error: null
}
const reducers = [
{
type: 'USERS_REQUEST',
reduce: state => ({
loading: true
})
},
{
type: 'USERS_REQUEST_SUCCESS',
reduce: (state, { users }) => ({
data: users,
loading: false
})
},
{
type: 'USERS_REQUEST_FAIL',
reduce: (state, { error }) => ({
error,
loading: false
})
}
]
// function which this library exports
export default makeReducerHandler(reducers, initialState)
This library exports only one function: makeReducerHandler
It takes two arguments: reducers array and initial state object.
A reducer is an object with structure:
{
type: 'USERS_REQUEST' // An action type string, optional
filter: (actionType, action) => actionType === 'USERS_REQUEST' // A function that should return boolean. Used for alternate filtering, optional
reduce: (state, action) => ({
loading: true
}) // A reducer that is expected to return new state, required
}
Either the type or filter must be provided
It handles 1 level of state merge
So you can use
const reducer = state => ({ loading: true })
instead of
const reducer = state => ({ ...state, loading: true })