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.
- change
onClick={getData()}
onClick={getData}
- 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
How to Force Clients to Refresh JavaScript Files
Draw a Connecting Line Between Two Elements
How to Replace Double/Multiple Slash to Single in Url
How to Show Roles of User Discord.Js/Userinfo Command
How to Change Size of Mat-Icon on Angular Material
How to Check a Radio Button in the Table Row Based on That Column Header
Safari Browser Audio.Play() Is Not Working
How to Display an Image from an Array of Images in React
Require(Img Path) Not Working/ Cannot Find Module "." Reactjs
Scroll to Element from Typescript Code (Angular 5)
How to Pass Array Variable from View to Controller in Spring MVC
How to Specify a Single File to Be Seed Only
How Add a New Key/Value Pair to a Json Object
Browserify :- Uncaught Typeerror: Fs.Readfilesync Is Not a Function
How to Show Which Question a User Is on When Taking My Quiz
Javascript or Jquery Browser Back Button Click Detector
Uncaught Typeerror: Cannot Read Property 'Click' of Null Chrome Extension