Observe Localstorage Changes in Js

Listen / Observe - changes in LocalStorage using store.js

I had a similar issue with store.js so I end up using pure localStorage and event listener approach to implement the problem.

Here is the working JSFiddle: Detect localStorage change on another browser tab

Explanation:

This makes use of Web Storage API.

You can create new localStorage key-value pair using a call to,

localStorage.setItem("current_tenant", "Tenant1");

Now whenever this storage is changed, StorageEvent is fired. This event is only sent to other windows.

The StorageEvent is fired whenever a change is made to the Storage object (note that this event is not fired for sessionStorage changes). This won't work on the same page that is making the changes — it is really a way for other pages on the domain using the storage to sync any changes that are made. Pages on other domains can't access the same storage objects. Source: MDN Web Docs

You can then add event listener on this storage and detect changes using event properties, oldValue and newValue
Eg,

Converted your example into JSFiddle and here is the solution that combines both storeJS and StorageEvent

Listen for changes with localStorage on the same window

Since JS is dynamical language just rewrite original functions.

var originalSetItem = localStorage.setItem; 
localStorage.setItem = function(){
document.createEvent('Event').initEvent('itemInserted', true, true);
originalSetItem.apply(this, arguments);
}

Change in localstorage not triggering event listener

There are two things wrong.

  1. change onClick={getData()} onClick={getData}
  2. From the doc(https://developer.mozilla.org/en-US/docs/Web/API/Window/storage_event). The storage event of the Window interface fires when a storage area (localStorage or sessionStorage) has been modified in the context of another document. Note the last sentence that says it won't be fired in the same document. You can see that if you open https://codesandbox.io/s/spring-browser-89con in 2 tabs in same browser, the alert will start coming.

Detecting if there is a change in a localStorage variable

There's a storage event on window object for local storage changes.

MDN local storage api

So you can watch the changes. But, if I am correct, that would work only for the same domain frames. So if they are, this is your choice.

How to make useEffect listening to any change in localStorage?

You can't re-run the useEffect callback that way, but you can set up an event handler and have it re-load the todos, see comments:

useEffect(() => {
// Load the todos on mount
const todosString = localStorage.getItem("todos");
if (todosString) {
const todos = JSON.parse(todosString);
setTodos(todos);
}
// Respond to the `storage` event
function storageEventHandler(event) {
if (event.key === "todos") {
const todos = JSON.parse(event.newValue);
setTodos(todos);
}
}
// Hook up the event handler
window.addEventListener("storage", storageEventHandler);
return () => {
// Remove the handler when the component unmounts
window.removeEventListener("storage", storageEventHandler);
};
}, []);

Beware that the storage event only occurs when the storage is changed by code in a different window to the current one. If you change the todos in the same window, you have to trigger this manually.



Related Topics



Leave a reply



Submit