2 min read
localStorage, sessionStorage 📂
Posted byThức Trần

Let's say, you're implementing a feature that functions based on the browser's storage, such as local storage or session storage.
You manipulate the storage programmatically based on the feature's events and use that data in the storage to do something. However, you might run into an issue which you're not getting the correct storage data - in other words - you're getting outdated information.
But why? Even though you've been listening to the Storage event!
const handleStorageChange = event => { if (event.key ==='myKey')) { // DO SOMETHING } } window.addEventListener('storage', handleStorageChange)
Listen to "storage" event
It is because of
The storage event of the Window interface fires when a storage area (localStorage or sessionStorage) has been modified in the context of another document.
So... this will only fire when the storage is modified in another tab/window of the same app.
After looking around on the Internet, trying out, I've found what I was missing.
Solution: Add this line into everywhere you perform an update to the storage.
sessionStorage.setItem('myKey', 'myNewValue') // Add this dispatchEvent below dispatchEvent( new StorageEvent('storage', { key: 'myKey', newValue: 'myNewValue' }) )
Dispatch storage event after performing an update to the storage
Now, handleStorageChange probably gets the event!
For example: if the component that enables the event listener is unmounted before handleStorageChange receives any updates, it will lose the event.
Posted by