DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

Notifications from LocalStorage with Signals

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:

Image description

Using the Rxjs fromEvent function, we can turn the above event listener into an Observable:

Image description

And if we're using Angular 16+, we can turn the above Observable into a Signal with one more function:

Image description

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:

Image description

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:

Image description


Let’s get connected! You can find me on:

Top comments (1)

Collapse
 
artydev profile image
artydev

Great thank you :-)