0.2.1 • Published 5 years ago

re-reducer v0.2.1

Weekly downloads
2
License
MIT
Repository
github
Last release
5 years ago

re-reducer

badge:travis badge:npm-version badge:npm-downloads badge:issues badge:license

a helper for create Flux Standard Action reducer

Installation

To install the stable version:

npm install re-reducer --save

or

yarn add re-reducer

Usage

import { createReducer, compose } from 're-reducer'

function change(state, action) {
  return action.payload
}

function increment(state, action) {
  return state + action.payload
}

function decrement(state, action) {
  return state - action.payload
}

function incrementEnhancer(next) {
  return (state, action) => {
    const {
      meta: {
        type
      } = {}
    } = action

    return type === 'increment' ? increment(state, action) : next(state, action)
  }
}

function decrementEnhancer(next) {
  return (state, action) => {
    const {
      meta: {
        type
      } = {}
    } = action

    return type === 'decrement' ? decrement(state, action) : next(state, action)
  }
}

const counterReducer = createReducer({
  namespace: 'counter',
  initialState: 0,
  handles: {
    change,
    increment,
    decrement
  },
  actionEnhancer(next) {
    return (payload, type) => {
      return next(payload, undefined, type && {type})
    }
  },
  handleEnhancer: compose(incrementEnhancer, decrementEnhancer)
})

const initialState = 1
let nextState

nextState = counterReducer(initialState, counterReducer.actions.change(10))
console.log('state change from %s to %s.', initialState, nextState)
// state change from 1 to 10.

nextState = counterReducer(initialState, counterReducer.actions.increment(10))
console.log('state increment from %s to %s.', initialState, nextState)
// state increment from 1 to 11.

nextState = counterReducer(initialState, counterReducer.actions.change(10, 'increment'))
console.log('state increment from %s to %s.', initialState, nextState)
// state increment from 1 to 11.

nextState = counterReducer(initialState, counterReducer.actions.decrement(10))
console.log('state decrement from %s to %s.', initialState, nextState)
// state decrement from 1 to -9.

nextState = counterReducer(initialState, counterReducer.actions.change(10, 'decrement'))
console.log('state decrement from %s to %s.', initialState, nextState)
// state decrement from 1 to -9.
0.2.1

5 years ago

0.2.0

5 years ago

0.1.4

7 years ago

0.1.3

7 years ago

0.1.2

7 years ago

0.1.1

7 years ago

0.1.0

7 years ago