How to synchronize state between diffrent tabs in NGXS

Viewed 251

I have a problem with synchronize state between multiple tabs. Here is scenario. I have actions RefreshToken and RefreshTokenSucces to refresh user token. Eferything is working fine until I open my app in two browser tabs. Now when token is expired and I am refreshing it succesfullly in active tab, but when i returned to the second tab state is outdated and request with old token are send which logoing out the user. Have you any suggestions how to keep auth data up to date in second tab after token is refreshed in first one?

  @Action(RefreshToken)
  public refresh(ctx: StateContext<AuthEntity>): Observable<void | Observable<void>> {
    const state = ctx.getState();
    return this.authHttpService.refreshToken(state).pipe(
      map((data) => ctx.dispatch(new RefreshSuccess(data))),
      catchError(() => {
        return ctx.dispatch(new Logout());
      })
    );
  }

  @Action(RefreshSuccess)
  public refreshSuccess(ctx: StateContext<AuthEntity>, action: RefreshSuccess): void {
    const state = ctx.getState;
    ctx.setState({...state, ...AuthEntity.fromData(action.payload)});
  }
0 Answers
Related