Hongbo Miao Hongbo Miao - 2 months ago 62
TypeScript Question

How to reset all states of ngrx/store?

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
})
)
]);

Answer

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:

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.

Comments