No boilerplate with Redux-Leaves: advanced usage

node v12.22.12
version: 1.1.1
endpointsharetweet
const { createStore } = require('redux') const { reduxLeaves, bundle } = require('redux-leaves') const initialState = { project: { agency: { name: 'Devs2U', revenue: 50000, costs: 80000 }, client: { name: 'MegaCorp', revenue: 1500000, costs: 7400000 }, budgeted: { days: 2, salaries: 10000 }, stagesCompleted: { discover: false, design: false, develop: false, test: false }, technologies: { languages: ['javascript'], libraries: ['react'] } }, persons: [ { name: 'Maisy Ware', title: 'CTO', employedBy: 'agency', status: 'determined' }, { name: 'Maddie Swanson', title: 'CTO', employedBy: 'client', status: 'anxious' }, { name: 'Kian Bernard', title: 'Junior Developer', employedBy: 'agency', status: 'eager' } ] }
All of our setup is below:
// break-even at arbitrary leaf state const breakEven = leafState => { return { ...leafState, revenue: leafState.costs // set revenue property equal to the costs property } } // set all properties at arbitrary leaf state // payload received will be the value to set const setAll = (leafState, action) => { const leafKeys = Object.keys(leafState) const newEntries = leafKeys.map(key => [key, action.payload]) return Object.keys(newEntries) } // set some property for all elements of an array const setEach = { reducer: (leafState, { payload: { prop, val } }) => { return leafState.map(element => ({ ...element, [prop]: val })) }, argsToPayload: (prop, val) => ({ prop, val }) } const [reducer, actions] = reduxLeaves(initialState, { breakEven, setAll, setEach }) const store = createStore(reducer) store.getState()
Now we can trigger this custom reducer logic at an arbitrary leaf of our store's state tree
// make both agency and client breakeven store.dispatch(actions.project.agency.create.breakEven()) store.dispatch(actions.project.client.create.breakEven()) store.getState()
// mark all stages complete store.dispatch(actions.project.stagesCompleted.create.setAll(true)) store.getState()
// give each person a happy status store.dispatch(actions.persons.create.setEach('status', 'happy')) store.getState()
Play around as you see fit!
Loading…

no comments

    sign in to comment