How to Keep Your Tabs in Sync with Local Storage

How to Keep Your Tabs in Sync with Local Storage

Keeping them synced can be a headache

You might come across instances where you have to change some data in one tab, and it should be reflected on another. The best example for this would be a live scoring system where you change the score in one tab, and the live score should be reflected on another. If you tried googling, most of the solutions would be based on a state management library such as NGXS, Redux, etc.

If you are deep into your project and do not have the time to install a state management library, this article will help you with a small trick.

Demo

1_XFbsJjAOhEHVAnjOJUgzCQ.gif

You will be able to achieve something like this by the end of this tutorial.

“Talk is cheap. Show me the code.”― Linus Torvalds

Hence let’s get our hands dirty with some code. 😉

This piece of code basically sets a value to the local storage. This code snippet should be implemented in the tab where the change in data is happening.

This code snippet adds an event listener to the storage event and runs the function passed in as the second argument every time the listener is triggered. This setListener function should be added on the tab where the change should be reflected. This function should be written inside the constructor of the component preferably.

Conclusion

Although this is not the optimal solution, and you should always invest in a state management library for instances like this, there are situations where you cannot afford to do so. In situations like that, this solution will be a handy tool for you. You can develop this solution further to suit your comfort. The below article can help you get going.

I hope you gained something from this. Farvel!!