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

Money Chaudhary
Sep 9, 2018 · 1 min read

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

Written by

Full Stack Developer @Devslane, Experienced in Angular4+, Django and Laravel for more than 2 years.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade