horiuchi / hard-reducer

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

hard-reducer

Type friendly facade for better reducer.

npm install hard-reducer -S
# or
yarn add hard-reducer

Concepts

  • Type safe interface
  • Avoid redundant type string definitions
  • Keep reducer interface (State, Action) => State to use with redux.combineReducers()
  • Handle Flux Standard Action <Payload>{ type: string, payload: Payload }

Check this code to know detail.

Flow playground

Examples

/* @flow */
import { buildActionCreator, createReducer } from 'hard-reducer'
const { createAction } = buildActionCreator({ prefix: 'counter/' })

const inc = createAction('inc', (val: number) => val)
const dec = createAction('dec', (val: number) => val)

inc(1) //=> { type: 'counter/inc', payload: 1 }

type State = { value: number }

const initialState = { value: 0 }

const reducer = createReducer(initialState)
  // Handle `(State, Payload) => State` in matched context.
  .case(inc, (state, payload) => {
    return {
      value: state.value + payload
    }
  })
  .case(dec, (state, payload) => {
    // $ExpectError
    const p: string = payload
    return {
      value: state.value - payload
    }
  })

// Use it
const ret0 = reducer(initialState, inc(3))
const ret1 = reducer(ret1, dec(1))

Use with explicit types.

/* @flow */
import { buildActionCreator } from 'hard-reducer'
import type { ActionCreator, Reducer } from 'hard-reducer/types'

const { createAction } = buildActionCreator({ prefix: 'xxx/' })
const foo: ActionCreator<number, string> = createAction('foo', (val: number) =>
  val.toString()
)

const reducer: Reducer<{
  /* type definition */
}> = createReducer(/* initialState */)

See more on index.js.flow

Related projects

TODO

  • TypeScript support by index.d.ts
  • Error Cases

LICENSE

MIT

About


Languages

Language:JavaScript 81.1%Language:TypeScript 18.9%