NGRX - What is the best way to reset the entire state?

What is the best way to reset the entire state when we have different reducers? I am having problems with this when I use selectors, since it does not bring me the initial state when I do the reset

MetaReducer

import { ActionReducer } from '@ngrx/store';
import { UserActionTypes } from '../../actions/actionTypes';

export function clearStateReducer(reducer: ActionReducer<any>): ActionReducer<any> {
  return (state, action) => {
    if (action.type === UserActionTypes.Logout) {
      state = undefined;
    }
    return reducer(state, action);
  };
}

State Module

import { NgModule } from '@angular/core';
import { StateService } from './state.service';
import { StoreDevtoolsModule } from '@ngrx/store-devtools';
import { StoreModule } from '@ngrx/store';
import { appReducer } from './reducers';
import { getInitialState } from './state';
import { metaReducers } from './reducers/metaReducers';

@NgModule({
  imports: [
    StoreModule.forRoot(appReducer, {
      initialState: getInitialState(),
      metaReducers,
      runtimeChecks: {
        strictStateImmutability: false,
        strictActionImmutability: false,
        strictStateSerializability: false,
        strictActionSerializability: false
      }
    }),
    StoreDevtoolsModule.instrument({
      maxAge: 25
    })
  ],
  providers: [StateService]
})
export class StateServiceModule {}

Upvotes: 1

Views: 1957

Answers (2)

timdeschryver
timdeschryver

Reputation: 15505

You may not assign state, instead call the reducer with undefined:

export function clearStateReducer(reducer: ActionReducer<any>): ActionReducer<any> {
  return (state, action) => {
    if (action.type === UserActionTypes.Logout) {
      return reducer(undefined, action);
    }
    return reducer(state, action);
  };
}

Upvotes: 0

Tony
Tony

Reputation: 20092

You can reset like this by setting the state back to the initial state

export const postReducer = createReducer(
  initialState,
  on(PostActions.ResetState, (state) => {
    return { state: initialState };
  }),
);

Upvotes: 1

Related Questions