Dev GuideAPI Reference
Dev GuideAPI ReferenceUser GuideLegal TermsGitHubDev CommunityOptimizely AcademySubmit a ticketLog In
Dev Guide

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

  1. Create a custom state for the reducer.

    type CounterState = Readonly<{
      total: number;
    }>;
    const initialCounterState: CounterState = { total: 0 };
    
  2. 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,  
    	}),  
    });
    
  3. 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;
    
  4. Create CustomGlobalState from ApplicationState and new states.

    export type CustomGlobalState = {
      customReducerUsingImmer: CounterState;
      customReducerTraditional: CounterState;
    } & ApplicationState;
    
  5. Create 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.