reducers

Methods

(inner) createReducer(defaultState, …actionMap) → {function}

Given a list of one or more action map objects, return a reducer function to satisfy the reducer signature expected by redux core

Parameters:
Name Type Attributes Description
defaultState Object

will be passed to the resulting reducer function the first time it is run

actionMap Object <repeatable>

objects in which each key is an action types, and its value is an action handler functions that takes (state, action) as ordered arguments

Source:
See:
  • tests

Returns:

A reducer function that handles each action type specified as a key in its action map

Type
function
Example
const defaultState = {
  people: 1,
  beasts: 1,
}

const VANQUISH_BEAST = '@@/actionTypes/vanquishBeast';
function vanquishBeastHandler(state, action) {
  return {
    ...state,
    beasts: state.beasts - 1,
    weaponUsed: action.payload.weapon,
  }
}

const SUCCUMB_TO_BEAST = '@@/actionTypes/succumbToBeast';
function succumbToBeastHandler(state, action) {
  return {
    ...state,
    people: state.people - 1,
    lastWords: action.payload.lastWords,
  }
}

const reducer = createReducer(defaultState, {
  [VANQUISH_BEAST]: vanquishBeastHandler,
  [SUCCUMB_TO_BEAST]: succumbToBeastHandler,
})

const vanquishBeast = createAction(VANQUISH_BEAST);
reducer({}, vanquishBeast({ weapon: 'broom' }))
//=> { people: 1, beasts: 0, weapon: 'broom' }

const succumbToBeast = createAction(SUCCUMB_TO_BEAST);
reducer({}, succumbToBeast({ lastWords: 'tell my mom...' }))
//=> { people: 0, beasts: 1, lastWords: 'tell my mom...' }

(inner) reduceReducers(…reducers) → {function}

Creates a single reducer from an n length list of reducers

Parameters:
Name Type Attributes Description
reducers function <repeatable>

any number of reducer functions that take (state, action) as ordered arguments

Source:
See:
  • tests

Returns:

A reducer function contstructed by merging all given reducer functions

Type
function
Example
function reducerA(state, action) {
  return {
    ..state,
    a: action.payload,
  }
}

function reducerB(state, action) {
  return {
    ..state,
    b: action.payload,
  }
}

const combined = reduceReducers(reducerA, reducerB)
const defaultState = { sandwich: 'grilled cheese' }
const action = { payload: 'apply me' }

combined(defaultState, action)
//=> { sandwich: 'grilled cheese', a: 'apply me', b: 'apply me' }