@deppi/reducer
TypeScript icon, indicating that this package has built-in type declarations

0.0.0-development.5 • Public • Published

@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 the example.js file
  • yarn test: Run test suites
    • yarn test --watch: Run test suites in watch mode
    • yarn test --coverage: Run test suites and collect coverage
  • yarn build:prod: Builds the Typescript for production
  • yarn clean: Removes the ./dist/ folder
  • yarn build: Builds a new ./dist folder after removing any previous one
  • yarn prepublishOnly: FOR NPM USE ONLY Causes the package to be built right before being published

Package Sidebar

Install

npm i @deppi/reducer

Weekly Downloads

4

Version

0.0.0-development.5

License

MIT

Unpacked Size

131 kB

Total Files

13

Last publish

Collaborators

  • beardedtim