Search code examples
angularngrx-storereducers

How to give a ngrx reducer/ action a value to set the state to?


I'm using Angular ngrx for the first time and I'm trying to replace all the @Input()s and @Output()s in my 'standard beginner-project' by it. Incrementing and Decrementing the state is simple, but I wonder how I can give the set Action a specific value to set the state to.

const _dividerReducer = createReducer(
  initialState,
  on(increment, (state) => state + 1),
  on(decrement, (state) => state - 1),
  on(set, (state) => initialState)
);

I have tried something like this so far at my actions:

import { createAction } from "@ngrx/store";
export const set = (newValue:number) => createAction("[Divider Component] Set", { newValue });

But that is obviously not the way it works - even if I saw that the second argument in createAction() is the config.


Solution

  • Looks like the issue is in the reducer file. You are resetting the state to the initial value on the action set, i.e. on(set, (state) => initialState).

    The reducer for the set action should look something like below:

    export interface IDividerState {
     value:number;
    }
    
    export const initialState: IDividerState = {
     value: 0
    }
    
    const _dividerReducer = createReducer(
    initialState,
    on(increment, (state) => state + 1),
    on(decrement, (state) => state - 1),
    on(set, (state, {payload}) => ({
    value: payload
    }));
    

    Then your action for Set should have the payload which is the value you want to set:

    import { createAction, props } from "@ngrx/store";
    
    export const set = createAction(
      "[Divider Component] Set",
      props<{ payload: number }>()
    );