I am using Redux for state management.
How do I reset the store to its initial state?
For example, let’s say I have two user accounts (u1
and
The following solution worked for me.
I added resetting state function to meta reducers.The key was to use
return reducer(undefined, action);
to set all reducers to initial state. Returning undefined
instead was causing errors due to the fact that the structure of the store has been destroyed.
/reducers/index.ts
export function resetState(reducer: ActionReducer): ActionReducer {
return function (state: State, action: Action): State {
switch (action.type) {
case AuthActionTypes.Logout: {
return reducer(undefined, action);
}
default: {
return reducer(state, action);
}
}
};
}
export const metaReducers: MetaReducer[] = [ resetState ];
app.module.ts
import { StoreModule } from '@ngrx/store';
import { metaReducers, reducers } from './reducers';
@NgModule({
imports: [
StoreModule.forRoot(reducers, { metaReducers })
]
})
export class AppModule {}