Keeping Multiple Tab In Sync using NGXS state management library, Rxjs and localStorage

“Safety experts recommend that you keep a constant scan of all your vehicle’s mirrors while driving”

A week ago I saw a blog post about “Keeping multiple tab in sync” at here.

The author @Tim Deschryver was one of the NGRX library team member. And he has really great posts.

At this post I decided to write same concept with State management library for Angular called NGXS.

I think NGXS better pattern-library for angular.

Anyone wonder about why I prefer to use NGXS over NGRX, can read that post also; “Why I Prefer NGXS over NGRX

Lets back our topic;

  1. We’re going to use NGXS for state management in an angular app
  2. Save our ACTION name to localStorage
  3. Listen to window.storage event with fromEvent operator

As a result;

  1. We will change data in one tab, and another tab will update automatically.
  2. For a quick example we‘re goin to check login status. If the user logout in one tab, other will also redirect him to login page.

Demo App Video;

Full code at my github profile; https://github.com/mehmetakifalp/ngxs-keep-browser-tab-sync

StackBlitz Demo;

Steps;

Creating angular app with CLI

Adding NGXS dependencies to package.json

Creating Login, Logout state, action.

Login State
Login/Logout Actions

Usage of fromEvent from Rxjs

Login Component

Imports at App Module

Full Demo!

Thanks for reading! Next post I m planning to write about addEventListener vs fromEvent comparison.

Follow me at github : https://github.com/mehmetakifalp

Follow me at medium : https://medium.com/@mehmetakifalp