Listening for updates in local storage reactjs

瘦欲@ 提交于 2020-07-23 06:43:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!