I have an ngrx store with an initial state similar to:
const state = {
child1: {...},
child2: {...},
}
with an ActionReducerMap as follows:
const reducerMap = {
child1: reducer1,
child2: reducer2,
}
Now I'd like to add a 'loading' state at the same level as child1 and child2 to track the loading of both the children (which are interconnected). To achieve this, I updated the initial state as follows:
const state = {
child1: {...},
child2: {...},
loading: false,
}
And I tried to use metareducer that sits at the top of reducer1 and reducer2 like this:
export function metaReducer(reducer) {
return function reduce(state, action) {
switch(action.type) {
case CommonActionTypes.UpdateLoading: {
return {
...,
loading: action.loading
}
}
default:
return reducer(state, action);
}
}
}
I added this to the feature store as follows:
StoreModule.forFeature('myStore', compose(metaReducer, combineReducers)(reducerMap))
In the application I invoke the UpdateLoading actions during some effects that update the child1 and child2. However, this doesn't work as I expected it to.
- To begin with, the initial state does not honor the 'loading' variable at all - it still thinks the original state is
{
child1: {...},
child2: {...},
}
- The 'loading' variable in the state, is only updated when the UpdateLoading action is called. With all the subsequent actions, it is removed from the state. This is strange as the only reducer that acts on it is the meta-reducer while reducer1 and reducer2 act on child-states child1 and child2 respectively.
Is it the right approach to update a common state using meta-reducer? How can I make this work?
StoreModule.forRoot({ loading: loadingReducer })
– Andrei Gătej