Create a custom reducer
Describes how to create a custom reducer.
This article provides an example custom reducer in FrontEnd\modules\blueprints\example\src\Store\Reducers.ts
-
Create a custom state for the reducer.
type CounterState = Readonly<{ total: number; }>; const initialCounterState: CounterState = { total: 0 };
-
Create the reducer. Configured Commerce uses Immer reducers, but traditional reducers are also supported.
import createTypedReducer, { createTypedReducerWithImmer } from "@insite/client-framework/Common/CreateTypedReducer"; import { Draft } from "immer"; const customReducerUsingImmer = createTypedReducerWithImmer(initialCounterState, { "Custom/Immer/Add": (draft: Draft<CounterState>, action: { amount: number }) => { draft.total += action.amount; }, }); const customReducerTraditional = createTypedReducer(initialCounterState, { "Custom/Traditional/Add": (state: CounterState, action: { amount: number }): CounterState => ({ // You would normally use `...state` to copy the existing state, but this only has one property. total: state.total + action.amount, }), });
-
Add the
reducer
to the global list.import { AnyAction, reducers } from "@insite/client-framework/Store/Reducers"; (reducers as any).customReducerUsingImmer = customReducerUsingImmer; (reducers as any).customReducerTraditional = customReducerTraditional;
-
Create
CustomGlobalState
fromApplicationState
and new states.export type CustomGlobalState = { customReducerUsingImmer: CounterState; customReducerTraditional: CounterState; } & ApplicationState;
-
Create
CustomActions
from baseAnyActions
and new reducer types.type Reducers = { customReducerUsingImmer: typeof customReducerUsingImmer; customReducerTraditional: typeof customReducerTraditional; }; export type CustomActions = Parameters\<Reducers[keyof Reducers]>[1] | AnyAction;
You can find the widget for the custom reducer at FrontEnd\modules\blueprints\example\src\Widgets\ CustomReducerWidget.tsx.
Updated over 1 year ago