Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rehydrate state on logout #164

Open
temka1234 opened this issue Jul 30, 2020 · 3 comments
Open

Rehydrate state on logout #164

temka1234 opened this issue Jul 30, 2020 · 3 comments

Comments

@temka1234
Copy link

I want to reset store to its initial state on logout, but save localstorage keys.
Is there any solution to make it from the box?

My current solution is:

export function rootReducer(reducer: ActionReducer<State>): ActionReducer<State> {
  return function (state: State, action: any): State {
    const isLogout = action.type === fromActions.AuthActionTypes.Logout;

    let localStorageState;
    if (isLogout) {
      localStorageState = pickStorageKeys(state);
      state = undefined;
    }

    let newState = reducer(state, action);

    if (isLogout) {
      newState = deepmerge(newState, localStorageState);
    }

    return newState;
  };
}
@jaydeep987
Copy link

Exactly I have that requirement!

@aakash14goplani
Copy link

Create a new meta-reducer that will reset reducer's state back to initial state. So when the user logs out, the application's reducer state will be reset to initial satate & the keys will also be preserved.

Logout Reducer

export function logoutMetareducer(reducer: ActionReducer<State>) {
  return function (state: State, action: Action) {
    if (action.type === AuthUserActions.logoutUser.type) {
      return reducer(undefined, action);
    }

    return reducer(state, action);
  };
}

Action

enum AuthUserActionTypes {
  LOGOUT = '[Auth] User Logout'
}
const logoutUser = createAction(
  AuthUserActionTypes.LOGOUT
);

App State and Initial State configurations

export interface State {
  books: fromBooks.BooksState,
  auth: fromAuth.UserState
}

const initialState: State = {
  auth: {
    user: null,
    gettingStatus: false,
    error: null
  },
  books: {
    collection: [],
    activeBookId: null
  }
};

export const reducers: ActionReducerMap<State> = {
  books: fromBooks.reducer,
  auth: fromAuth.authReducer
};

export const metaReducers: MetaReducer<any, any>[] = [localStorageSyncReducer, logoutMetareducer];

@temka1234
Copy link
Author

Keys not preserved on logout.

Here is example:
https://stackblitz.com/edit/ngrx-seed-g4xhnm

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants