redux-leaves
Write once. Reduce anywhere.
Getting started
API reference
30 second demo
Write once.
npm install --save redux-leaves
import { createStore } from 'redux'
import reduxLeaves from 'redux-leaves'
// 1. Define initialState
const initialState = {
counter: 1,
list: ['first'],
nested: { arbitrarily: { deep: 0 } }
}
// 2. (Optional) Define custom reducers dictionary
const reducersDict = {
double: leafState => leafState * 2,
appendToEach: (leafState, action) => leafState.map(str => str.concat(action.payload)),
countKeys: (leafState, action, wholeState) => Object.keys(wholeState).length
}
// 3. Grab reducer and actions from reduxLeaves, then create the Redux store
const [reducer, actions] = reduxLeaves(initialState, reducersDict)
const store = createStore(reducer)
Reduce anywhere.
// *** KEY ***
// Default: an action creator that ships with Redux-Leaves by default
// Custom: an action creator generated by the custom reducersDict
// Default: increment state.counter
store.dispatch(actions.counter.create.increment())
console.log(store.getState().counter) // 2
// Custom: double state.counter
store.dispatch(actions.counter.create.double())
console.log(store.getState().counter) // 4
// Default: push 'second' to state.list
store.dispatch(actions.list.create.push('second'))
console.log(store.getState().list) // ['first', 'second']
// Custom: append ' item' to each element in state.list
store.dispatch(actions.list.create.appendToEach(' item'))
console.log(store.getState().list) // ['first item', 'second item']
// Default: assign true to key 'newKey' at the top-level of state
store.dispatch(actions.create.assign({ newKey: true }))
console.log(store.getState().newKey) // true
// Custom: update state.nested.arbitrarily.deep with state's number of top-level keys
store.dispatch(actions.nested.arbitrarily.deep.create.countKeys())
console.log(store.getState().nested.arbitrarily.deep) // 4
console.log(store.getState())
/*
{
counter: 4,
list: ['first item', ' second item'],
nested: { arbitrarily: { deep: 4 } }
}
*/
Testing
To run all tests locally:
git clone git@github.com:richardcrng/redux-leaves.git
cd redux-leaves && npm run test a
All tests are located alongside their relevant documentation in the docs folder.