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.
The combineReducers helper function turns an object whose values are different reducing functions into a single reducing function you can pass to createStore .
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.
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.
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.
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,
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With