How to reset the state or clear the store on logout in ngrx/store?

Money Chaudhary
1 min readSep 9, 2018

--

When we use ngrx/store in our app we need to clear the store on logout, Now the question comes to mind how we can do that? So, for this NgRx provides meta-reducer.

What is a Meta-Reducer?
A meta reducer is a high-level reducer that allows you to take action on global state.

How can we implement this?

export function clearState(reducer) {
return function (state, action) {

if (action.type === ActionTypes.LOGOUT) {
state = undefined;
}

return reducer(state, action);
};
}

This is the basic signature of meta-reducer. This function expects the reducer and also needs to return the reducer.

How can we add meta-reducer to our store?

@NgModule({
imports: [
StoreModule.forRoot(reducers, { metaReducers: [clearState] }),
],
declarations: [],
providers: [],
})

How does it work?

export class ActionTypes {
static LOGOUT = "[App] logout";
}

export class Logout implements Action {
readonly type = ActionTypes.LOGOUT;
}

If the action type is LOGOUT, we will return an undefined state. Then all other reducers will return the initial value.

this.store.dispatch(new Logout());

So, When user logout, we need to just dispatch the Logout action

--

--

Money Chaudhary

Computer Science Grad Student @ University of Southern California, LA. Experienced in React JS, Angular4+, Django, and NodeJS for more than 5years.