Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear State in the #ngrx?

Tags:

ngrx

I am building an mobile app using Ngrx and Angular2. I would like to clear the Store when user logout from my application? Can anyone know how to do this?

like image 982
Tuong Le Avatar asked Dec 15 '22 04:12

Tuong Le


2 Answers

You should have an clear action in each of your reducer, which will clean respective properties in the store. Dispatch clear actions in each of the reducer manually when you call logout. I am not sure right now if its there an option to clean the entire store in one go.

Alternative: A more cleaner and faster approach would be. Whenever you call an action via store.dispatch it calls all your reducers with that action.type. Say your action type name is CLEAR, put this action in each of your reducer to clear the respective property of the store. And call store.dispatch with action.type = 'CLEAR' ONCE, it will clear all the properties of the store.

If it confuses let me know, I will try to explain with code.

like image 86
Savaratkar Avatar answered Mar 20 '23 02:03

Savaratkar


The solution is to write the root reducer.

It's similar to this:

export function reducer(state: any, action: any): ActionReducer<any> {
    if (action.type === 'CLEAR STATE') {
        state = undefined;
    }

    return appReducer(state, action);
}

Check this: How to reset the state of a Redux store?

like image 39
Tuong Le Avatar answered Mar 20 '23 03:03

Tuong Le