Search code examples
angularngrx

Setting up reducers in Ngrx


I'm setting up very basic Ngrx state management.

# app.module
StoreModule.forRoot(reducers),

This code is generated with the Ngrx schematics generators.

export const reducers: ActionReducerMap<State> = {
  [fromFilter.filterFeatureKey]: fromFilter.reducer
};

Which gives me the error

Expression form not supported in 'reducers'

I've tried this which I found on the Ngrx github page. This doesn't give any errors but just silently doesn't work, no state is generated.

export function reducers(state: State | undefined, action: Action) {
  return combineReducers(_reducers)(state, action);
}

I can get it to work by hard-coding the filter key, however that is not the recommended practice according to the docs.

export const reducers: ActionReducerMap<State> = {
  filter: fromFilter.reducer
};

Solution

  • This is a problem with auto-generated code by the schematics right now. To keep the non-hardcoded dictionary version, use an injection token in your app.module.ts, like so (reducers and State are imported from your declaration):

    export const REDUCER_TOKEN = new InjectionToken<ActionReducerMap<State>>('root reducer');
    @NgModule({
        declarations: [AppComponent],
        imports: [
            ...
            StoreModule.forRoot(REDUCER_TOKEN),
        ],
        providers: [
            { provide: REDUCER_TOKEN, useValue: reducers }
        ],
        bootstrap: [AppComponent]
    })
    export class AppModule { }
    

    The problem only occurs when using ahead-of-time compilation, but since that's the default for most production builds, you have to use a token to get it to work.