问题
I have a form in which I ask users for their input. I will then store the input in the local storage.
let shape = {
shape: shape,
color: shapeColor,
dimension: noOfDimension,
}
arr.push(shape)
window.localStorage.setItem("arr", JSON.stringify(arr))
Now I have a button in which when I click on it, a modal pops up and display the shapes stored. The shape data can be retrieved by JSON.parse(localStorage.getItem("arr"))
. However the problem is, when I were to add new shape data again, it will not be reflected in the modal (unless I refresh). How can I keep listening to the local storage for updates? I have tried the following code:
useEffect(()=>{
function listenForStorage(){
const item = localStorage.getItem('arr')
if (item) {
setShapeList(item)
}
}
window.addEventListener('storage', listenForStorage)
return () => {
window.removeEventListener('storage', listenForStorage)
}
},[])
The useEffect is running, but somehow, the window.addEventListener
is not being accessed .
回答1:
the listener you set for localStorage does not work for the active tab. You must update the state while saving the data you need to do to localStorage.
Example
https://codesandbox.io/s/gracious-nobel-ezp8f?file=/src/App.js
Test using two tabs (console)
https://ezp8f.csb.app/
来源:https://stackoverflow.com/questions/62906923/listening-for-updates-in-local-storage-reactjs