Sometimes the simple atomic action creators - update
, set
, clear
... - won't feel sufficient.
The general purpose do
can help with flexibility: it takes a callback of (leafState, treeState) => newLeafState
.
const pizzaShopState = {
stock: {
margherita: 10,
pepperoni: 20
},
isOpen: {
forEatIn: false,
forTakeOut: true
}
}
const [reducer, actions] = riduce(pizzaShopState)
const { getState, dispatch } = createStore(reducer)
const squareMargheritaStock = actions.stock.margherita.create.do(leafState => leafState ** 2)
dispatch(squareMargheritaStock)
getState().stock // => { margherita: 100, pepperoni: 20 }
const openIfSurplusStock = actions.isOpen.create.do(
(leafState, treeState) => {
const hasEnoughStock = treeState.stock.margherita > 10
return {
forEatIn: leafState.forEatIn || hasEnoughStock,
forTakeOut: leafState.forTakeOut || hasEnoughStock
}
}
)
getState().isOpen // => { forEatIn: true, forTakeOut: true }