How to sync Redux state between two tabs after localStorageChange

1.2k Views Asked by At

I have a probelm with my redux state and loggin of. When I am using two tabs and log of from one my state is not sync between tabs. I have a redux and redux-observabel set:

epic

const signOutEpic = (action$: ActionsObservable<Types.ISignOutAction>) =>
  action$.pipe(
    ofType(Consts.SIGN_OUT),
    switchMap(() =>
      DeviceHelper.getDeviceInfo().then((device: IUserDeviceModel) =>
        DataProvider.signOut(device)
          .then(() => Actions.signOutSuccess())
          .catch((error: IErrorModel) => Actions.signOutFailure(error))
      )
    )
  );

const signOutSuccessEpic = (
  action$: ActionsObservable<Types.ISignOutSuccessAction>
) =>
  action$.pipe(
    ofType(Consts.SIGN_OUT_SUCCESS),
    map((_action: Types.ISignOutSuccessAction) => {
      return StorageHelper.deleteUser().then(() => {
        return StorageManager.deleteValue("session");
      });
    }),
    mapTo(replace(ROUTES.LOGIN))
  );

types:

export interface ISignOutAction {
  type: typeof Consts.SIGN_OUT;
}

export interface ISignOutSuccessAction {
  type: typeof Consts.SIGN_OUT_SUCCESS;
}

export interface ISignOutFailureAction {
  type: typeof Consts.SIGN_OUT_FAILURE;
  error?: IErrorModel;
}

reducer:

 case Consts.SIGN_OUT_SUCCESS:
    case Consts.REFRESH_TOKEN_FAILURE: {
      return {
        ...state,
        isAuthenticated: false,
        session: undefined,
        user: undefined,
      };
    }

and actions

export const signOut = (): ISignOutAction => {
  return {
    type: Consts.SIGN_OUT,
  };
};

export const signOutSuccess = (): ISignOutSuccessAction => {
  return {
    type: Consts.SIGN_OUT_SUCCESS,
  };
};

export const signOutFailure = (error?: IErrorModel): ISignOutFailureAction => {
  return {
    error,
    type: Consts.SIGN_OUT_FAILURE,
  };
};

So login of is working, but every time i have two tabs open and log of from one, second one is still sitting with state for logged user. My localStorage is changing and i have informataion for anonymus user. But my state is not synced although sign out action is working correctly. Id di a workound for this in one component with:

 window.addEventListener("storage", getUserId);

  return () => {
    window.removeEventListener("storage", getUserId);
  };

But i think this requiers a more global solution. I know that tthere is a lib for this, but i do not want to use a 3rd party stuff.

Any ideas how to get this done with current setup?

0

There are 0 best solutions below