@deppi/reducer
v0.0.0-development.5
Published
Helper package for creating a reducer for Flux-like stores using Kmett-style lenses
Downloads
14
Maintainers
Readme
@deppi/reducer
Handling updating state, the functional way
Usage
// import functions
import { setStateOn, createReducer } from '@deppi/reducer'
// Declare some types, if that's your thing
interface State {
name: string;
}
// We define some action that will
// trigger the updates
interface UpdateUserAction extends Action {
payload: {
name: string;
}
}
// Have some initial state
const data: State = {
name: 'tim'
}
// and a lens to the part we are updating
const nameLens = lensProp('name')
// We create an updater
const setUserName = setStateOn<State, string>(nameLens)
const reducer = createReducer({
// and when the action UPDATE_USER_NAME
// goes through our reducer
['UPDATE_USER_NAME']: [
// we want to update the user's name as John
setUserName.as('John'),
// will, again, update the user's name to John
setUserName.using<UpdateUserAction>((action, state) => action.payload.name),
// This will set the name to JOHN since these
// are ran in sequence and passed the next
// state value
setUserName.with<UpdateUserAction>(
() => oldName => oldName.toUpperCase()
)
]
})
// At some point we get given a new action
// that matches our ActionHandlers
// and we pass it the previous
// state
console.log(reducer(data, {
type: 'UPDATE_USER_NAME',
payload: {
name: 'John'
}
}))
// { name: 'JOHN' }
Scripts
yarn example
: Runs theexample.js
fileyarn test
: Run test suitesyarn test --watch
: Run test suites in watch modeyarn test --coverage
: Run test suites and collect coverage
yarn build:prod
: Builds the Typescript for productionyarn clean
: Removes the./dist/
folderyarn build
: Builds a new./dist
folder after removing any previous oneyarn prepublishOnly
: FOR NPM USE ONLY Causes the package to be built right before being published