Search code examples
angularngrx

How to use method CreateReducer in ActionReducerMap<State> object?


I want to create reducer by CreateReducer method, but I don't understand why it's not work.

I tried change State class, but I think it's not way to go.

export const reducers: ActionReducerMap<State> = {
  productsReducer: createReducer(initialState, on(ProductListActions.toggleImage), state => )
};

Argument of type '(state: any) => any' is not assignable to parameter of type 'On'. Type '(state: any) => any' is missing the following properties from type 'On': reducer, types


Solution

  • Because you don't use the brackets correctly. Remove the bracket after toggleImage and use it after the function. You can see the issue if you make more use of indentation. And you must return a state as well, because a reducer is a function that applies an action to a state and returns the new state afterwards.

    export const reducers: ActionReducerMap<State> = {
      productsReducer: createReducer(
        initialState,
        on(ProductListActions.toggleImage, state => state) // <-- This ) is missing and removed after toggleImage
      )
    };
    

    In addition to that, you'll want to wrap it into another function, otherwise the AOT compiler will throw an error. See docs and this post.