Issue
I am using Angular 2 with ngrx/store. I want to reset the whole store states when user dispatch USER_LOGOUT
.
I read the Dan Abramov's answer of How to reset the state of a Redux store?, but I didn't figure out how to write rootReducer
correctly and where to put it when using ngrx/store.
Or is there any other way to handle this in ngrx/store?
bootstrap(App, [
provideStore(
compose(
storeFreeze,
storeLogger(),
combineReducers
)({
router: routerReducer,
foo: fooReducer,
bar: barReducer
})
)
]);
Solution
This answer is specific to ngrx version 2. The question has another, more recent answer that explains how the same can be done with ngrx version 4.
compose
builds the ngrx root reducer.
The arguments passed to compose
are functions that return a reducer - composed from the reducer they themselves are passed as an argument. You can compose the resetting of your store like this:
import { compose } from "@ngrx/core/compose";
...
bootstrap(App, [
provideStore(
compose(
storeFreeze,
storeLogger(),
(reducer: Function) => {
return function(state, action) {
if (action.type === 'USER_LOGOUT') {
state = undefined;
}
return reducer(state, action);
};
},
combineReducers
)({
router: routerReducer,
foo: fooReducer,
bar: barReducer
})
)
]);
Note that this will reset all of the store's state - including the router
. If that's not what you want, you could tweak the example.
With introduction of NgModule
the bootstrapping has changed, but you still pass the composed reducer to provideStore
:
import { compose } from "@ngrx/core/compose";
import { StoreModule } from "@ngrx/store";
@NgModule({
...
imports: [
...
StoreModule.provideStore(compose(...))
],
...
Answered By - cartant
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.