LocalStorage can be used as a persistent cache to store our data in the browser.
LocalStorage can be used to share data between multiple tabs that render the same application. Even better, there is a storage event that can be listened to to know when another tab updated LocalStorage:
Using the Rxjs fromEvent function, we can turn the above event listener into an Observable:
And if we're using Angular 16+, we can turn the above Observable into a Signal with one more function:
The above Signal could be used in a service to synchronize data between tabs. Spying on that Signal to see what’s going on in it is as easy as registering a side-effect on it using the effect function:
Note that trying to update a Signal within an effect() is not allowed by default, as it could trigger unwanted behavior (infinite loop such as SignalA triggers an update of SignalB that updates SignalC that updates SignalA - and around we go).
That said, if you know what you're doing and are 100% sure that you won't trigger an infinite loop, you can override that setting with the optional parameter allowSignalWrites as follows:
Let’s get connected! You can find me on:
- Medium: https://medium.com/@nhannguyendevjs
- dev.to: https://dev.to/nhannguyendevjs
- Linkedin: https://www.linkedin.com/in/nhannguyendevjs/
- X (formerly Twitter): https://twitter.com/nhannguyendevjs