btroncone / ngrx-store-localstorage

Simple syncing between @ngrx store and local storage

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Rehydrate state on logout

temka1234 opened this issue · comments

commented

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;
  };
}
commented

Exactly I have that requirement!

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];
commented

Keys not preserved on logout.

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