Create a custom reducer
This article describes the process for creating 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 from ApplicationState and new states.
export type CustomGlobalState = {
customReducerUsingImmer: CounterState;
customReducerTraditional: CounterState;
} & ApplicationState;
- Create new CustomActions from base AnyActions 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 2 months ago