onAction

Creates a sub-reducer for a particular action type.

// JavaScript
function onAction(type, getNextState?)
// TypeScript
function onAction<
S = any,
T extends string | symbol | number = any,
A extends Action<T> = AnyAction
>(
type: T,
actionReducer: SubReducer<S, A>
): SubReducer<S>
function onAction<
S = any,
A extends Action = AnyAction
>(
actionCreator: TypedActionCreator<A>,
actionReducer: SubReducer<S, A>
): SubReducer<S>

Details

createAction returns a sub-reducer that checks each incoming action's type against the one specified and, on a match, delegates to the passed reducer-like getNextState function. For non-matching actions, the sub-reducer simply returns the unchanged input state.

The action type to match against can be specifed in two ways. The simplest way is to pass the action type value. Alternatively, you can pass an action creator generated by createAction; in this case, the action creator's type property is used to determine the action type.

Note that the function returned by onAction is a sub-reducer - rather than proper Redux reducer - because it does not provide an initial state. Instead, it expects to be embedded into a full reducer which takes care of state initialization. Such a reducer can be generated using withInitialState and its subReducer parameter, or by combining withInitialState and chainReducers.

TypeScript Notes

If you specify the action type using a createAction action creator, the type of the getNextState function's action parameter will be automatically inferred from the type of the action creator.

import { createAction, onAction } from 'redux-preboiled'
const multiply = createAction('multiply').withPayload<number>()
// multiply: PayloadActionCreator<number>
const multiplySubReducer = onAction('multiply', (state, action) => {
// action: PayloadAction<number, 'multiply'>
return state * action.payload
})

Examples

Basic usage:

import { onAction } from 'redux-preboiled'
const subReducer = onAction(
'multiply',
(state, action) => state * action.payload
)
subReducer(2, { type: 'multiply', payload: 4 })
// => 8
subReducer(2, { type: 'increment' })
// => 2

Specifying the action type with a createAction action creator:

import { createAction, onAction } from 'redux-preboiled'
const increment = createAction('increment')
const multiply = createAction('multiply').withPayload()
const subReducer = onAction(
multiply,
(state, action) => state * action.payload
)
subReducer(2, multiply(4))
// => 8
subReducer(2, increment())
// => 2

See Also