I am having some troubles with the state of a redux app. Let's say that a couple of actions update the state. When an NgRX effect is triggered then suddenly the state disappears and the next action that goes to the reducer takes the initialState.
Here is my effect:
@Effect() getConfiguration$ = this.actions$.pipe(
ofType(PlasmaAction.PlasmaActionTypes.GET_CONFIGURATION),
switchMap((action: PlasmaAction.PlasmaActions) => {
return this.plasmaService.send(action.payload).pipe(
map(result => {
return new PlasmaAction.SetConfiguration(result);
})
);
})
);
Up to dispatching the GET_CONFIGURATION action the state is fine, but then the state looks this way: redux-dev-tools-screenshot and the state is empty. Am I missing something?
P.S. The SET_CONFIGURATION is dispatched and updates the state with the new configuration and all other attributes are back to the initial ones.
@EDIT: Here is my reducer. With a little bit of debugging from my side:
export function plasmaReducer(state: PlasmaState, action: PlasmaActions) {
if (!state) {
console.log('%c STATE IS EMPTY', 'color:red;');
state = initialState;
}
switch (action.type) {
case PlasmaActionTypes.CONNECTION_OPENED: {
return { ...state, connected: true };
}
case PlasmaActionTypes.CONNECTION_CLOSED: {
return { ...state, connected: false };
}
case PlasmaActionTypes.SET_CONFIGURATION: {
return { ...state, configuration: action.payload };
}
}
}
You reducer should always have a default
case.
Every action is passed through every reducer loaded in your application. This means if you don't handle the "other" actions inside your reducer the reducer returns undefined
, hence the empty state you see.
To handle the "other" actions, use a default
case and simply return the state as is:
switch (action.type) {
case PlasmaActionTypes.CONNECTION_OPENED: {
return { ...state, connected: true };
}
case PlasmaActionTypes.CONNECTION_CLOSED: {
return { ...state, connected: false };
}
case PlasmaActionTypes.SET_CONFIGURATION: {
return { ...state, configuration: action.payload };
}
default:
return state;
}