angulartypescriptstate-managementngxs

How to sync the state data saved in localstorage across all tabs using `Ngxs` state management?


I am saving all data of the state after converting it to base64 format using Ngxs state management library. I can get all data across all tabs. But if I change a data in one tab it does not sync in the other tabs. To sync the data I have to refresh the tab. Is there any way to sync full state in all tabs if the state is changed in one tab?

Here is my code of AppModule:

@NgModule({
  declarations: [
    AppComponent,
    ReadComponent,
    CreateComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    NgxsModule.forRoot([
      TutorialState
    ]),
    NgxsReduxDevtoolsPluginModule.forRoot(),
    NgxsLoggerPluginModule.forRoot(),
    NgxsStoragePluginModule.forRoot({
      storage: StorageOption.LocalStorage,
      serialize: (state) => btoa(JSON.stringify(state)),
      deserialize: (state) => JSON.parse(atob(state))
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {
}

Solution

  • I have solved this issue by subscribing the storage event in the root component.

      ngAfterContentInit(): void {
        let source$ = fromEvent<StorageEvent>(window, 'storage');
    
        source$.subscribe(data => {
          this.store.reset(JSON.parse(atob(localStorage['@@STATE']));
        });
    
      }
    

    Using this code all tabs synchronizes automatically.