re-reducer
v0.2.1
Published
a helper for create Flux Standard Action reducer
Downloads
7
Readme
re-reducer
a helper for create Flux Standard Action reducer
Installation
To install the stable version:
npm install re-reducer --save
or
yarn add re-reducer
Usage
import { createReducer, compose } from 're-reducer'
function change(state, action) {
return action.payload
}
function increment(state, action) {
return state + action.payload
}
function decrement(state, action) {
return state - action.payload
}
function incrementEnhancer(next) {
return (state, action) => {
const {
meta: {
type
} = {}
} = action
return type === 'increment' ? increment(state, action) : next(state, action)
}
}
function decrementEnhancer(next) {
return (state, action) => {
const {
meta: {
type
} = {}
} = action
return type === 'decrement' ? decrement(state, action) : next(state, action)
}
}
const counterReducer = createReducer({
namespace: 'counter',
initialState: 0,
handles: {
change,
increment,
decrement
},
actionEnhancer(next) {
return (payload, type) => {
return next(payload, undefined, type && {type})
}
},
handleEnhancer: compose(incrementEnhancer, decrementEnhancer)
})
const initialState = 1
let nextState
nextState = counterReducer(initialState, counterReducer.actions.change(10))
console.log('state change from %s to %s.', initialState, nextState)
// state change from 1 to 10.
nextState = counterReducer(initialState, counterReducer.actions.increment(10))
console.log('state increment from %s to %s.', initialState, nextState)
// state increment from 1 to 11.
nextState = counterReducer(initialState, counterReducer.actions.change(10, 'increment'))
console.log('state increment from %s to %s.', initialState, nextState)
// state increment from 1 to 11.
nextState = counterReducer(initialState, counterReducer.actions.decrement(10))
console.log('state decrement from %s to %s.', initialState, nextState)
// state decrement from 1 to -9.
nextState = counterReducer(initialState, counterReducer.actions.change(10, 'decrement'))
console.log('state decrement from %s to %s.', initialState, nextState)
// state decrement from 1 to -9.