Skip to main content

ReducerBuilder

The function returned from createReducer.

A ReducerBuilder is a reducer - it can be used directly as a reducer passed to createStore() or React's useReducer() hook.

ReducerBuilders also have a .reduce() method that can be used to extend the reducer's capabilities.

Example

import { createReducer } from '@zedux/react'

const reducer = createReducer([1, 3])
.reduce('add', (state, payload) => [...state, payload])
.reduce('remove', (state, payload) =>
state.filter(num => num !== payload)
)

function Numbers() {
const [numbers, dispatch] = useReducer(builder)
...
}

Definition

type SubReducer<
State = any,
Payload = any,
Type extends string = string,
Meta = any
> = (
state: State,
payload: Payload,
action: Action<Payload, Type, Meta>
) => State

interface ReducerBuilder<State = any> extends Reducer<State> {
reduce<Payload = any, Type extends string = any, Meta = any>(
reactable: Reactable<Payload, Type> | Reactable<Payload, Type>[],
subReducer: SubReducer<State, Payload, Type, Meta>
): ReducerBuilder<State>
}
reduce

A function that accepts an action type and a "sub-reducer" and returns the ReducerBuilder for chaining.

The action type can be any of the following:

  • A string.
  • An ActionFactory with .type property attached.
  • A list containing any combination of the above.

The sub-reducer is a function that accepts the current state, the payload from the matched action, and the full action object, and should return the new state or the current state if no change.

.reduce([myActionFactory, 'myActionType'], (state, payload, action) => newState)

Most sub-reducers will only need the current state and action payload, so for convenience those are the first 2 parameters. Some sub-reducers need access to the full action object, so Zedux passes that as the 3rd param.

See Also