Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 713
Udi Mazor Avatar asked Nov 22 '18 09:11

Udi Mazor


People also ask

How does combine reducer work?

The combineReducers helper function turns an object whose values are different reducing functions into a single reducing function you can pass to createStore .

What is reducer slice?

createSlice is a higher order function that accepts an initial state, an object full of reducer functions and a slice name. It automatically generates action creators and action types that correspond to the reducers and state. In Redux-Toolkit, the createSlice method helps us create a slice of the redux-store.

What is redux slice?

Redux Slices​ A "slice" is a collection of Redux reducer logic and actions for a single feature in your app, typically defined together in a single file. The name comes from splitting up the root Redux state object into multiple "slices" of state.

Can reducers share state?

Yeah, if you want to "share", then those reducers are processing the same state, then you have to merge them into one reducer only. Because each reducer are mapping to a different slice of state, so the actions that modify the SAME state definitely go into the same reducer.


1 Answers

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,
});
like image 146
cyr_x Avatar answered Oct 31 '22 19:10

cyr_x