Search code examples
angulartypescriptngrxngrx-store

Splitting big reducer into smaller reducers


I have a feature reducer (slice reducer) called animals. I want to split these reducers to mammals, birds, fishes etc. This part is easy as I can simply use the ActionReducerMap.

Now let's say the mammals' reducer's state is huge and I want to split it to several smaller reducers i.e cat's family, dog's family etc. the ActionReducerMap is not returning a reducer and is not nestable. I tried searching the web for solution or example but I couldn't find. My question, in short, is how to make multi-level nested reducers.

export interface AnimalsState{
  mammals: fromMammals.mammalsState;
  birds: fromBirds.birdsState;
}

export const reducers: ActionReducerMap<AnimalsState> = {
  mammals: fromMammals.reducer,
  birds: fromBirds.reducer
};

I want to split mammals reducer into smaller reducers.


Solution

  • You can you can compose a new reducer using the combineReducers function from @ngrx/store, this will allow you to combine your dogs and cats reducers for the mammals state.

    I made a quick example of how to use it on stackblitz.

    The example of the combineReducers function can be found in app/store/mammals/mammals.reducer.ts:

    import { combineReducers } from '@ngrx/store';
    
    import { catsStoreName, catsReducer, CatsState } from '../cats';
    import { dogsStoreName, dogsReducer, DogsState } from '../dogs';
    
    
    export type MammalsState = {
      [catsStoreName]: CatsState,
      [dogsStoreName]: DogsState,
    }
    
    export const mammalsReducer = combineReducers<MammalsState>({
      [catsStoreName]: catsReducer,
      [dogsStoreName]: dogsReducer,
    });