HomeGuidesAPI Reference
Submit Documentation FeedbackJoin Developer CommunityOptimizely GitHubOptimizely NuGetLog In

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

  1. Create a custom state for the reducer.
type CounterState = Readonly<{
total: number;
}>;
const initialCounterState: CounterState = { total: 0 };
  1. 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,
    }),
});
  1. 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;
  1. Create CustomGlobalState from ApplicationState and new states.
export type CustomGlobalState = {
customReducerUsingImmer: CounterState;
customReducerTraditional: CounterState;
} & ApplicationState;
  1. 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