简体   繁体   中英

Listen localStorage in react(useEffect)

I am using some third-party libraries in react. That will make some local storage change on the page. I tried to listen to that local storage change using javascript storage event and give localStorage.getItem('test') as the dependency of useEffect. But it is not listening to the localStorage change.

Here is my code

useEffect(() => {
  window.addEventListener('storage', () => {
    console.log(JSON.parse(localStorage.getItem('test')));
  })
},[])

How to listen the localStorage event in react.

Based on this answer Listen for changes with localStorage on the same window

React version:

Add this code before the other script add anything to local storage

const originalSetItem = localStorage.setItem;

localStorage.setItem = function (key, value) {
  const event = new Event("itemInserted");

  event.value = value; // Optional..
  event.key = key; // Optional..

  document.dispatchEvent(event);

  originalSetItem.apply(this, arguments);
};

In your component:

useEffect(() => {
  const localStorageSetHandler = function (e) {
    alert('localStorage.set("' + e.key + '", "' + e.value + '") was called');
  };

  document.addEventListener("itemInserted", localStorageSetHandler, false);

  // remember to remove the listener
  return () =>
    document.removeEventListener("itemInserted", localStorageSetHandler);
}, []);

请参阅 codesandbox 上的示例

You can this way!

useEffect(() => {
  function checkLocalData() {
    const item = localStorage.getItem('test')

    if (item) {
      checkLocalData(item)
    }
  }

  window.addEventListener('storage', checkLocalData)

  return () => {
    window.removeEventListener('storage', checkLocalData)
  }
}, [])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM