React: sync with local storage
P粉214176639
P粉214176639 2024-02-03 23:49:55
0
1
453

Have a React application. Certain components will set different data values ​​to local storage using the same key over a period of time. I need to subscribe to several components of this project in local storage. Whenever a value with a specific key is updated in local storage, subscribed components should be notified or provided with the updated value in local storage.

I tried creating a custom hook for this and using with by adding an event listener to the storage event as shown below.

const useSyncLocalStorage = (key: string) => {
  const [storageVal, setStorageVal] = useState<string | null>(() => localStorage.getItem(key));

  const handleStorageChange = () => {
    const value = localStorage.getItem(key);
    setStorageVal(value);
  };

  useEffect(() => {
    window.addEventListener('storage', handleStorageChange);

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

  return storageVal;
};

and use it in a component like this:

const locationStored = useSyncLocalStorage('location');

I tried updating the local storage value on the click event, but the hook does not return the updated value in the local storage. I verified that the local storage value was updated in the dev tools. The problem appears to be that the storage event is not being fired in the same window/tab that caused the storage change.

Is there any way to subscribe to the value of localstorage?

P粉214176639
P粉214176639

reply all(1)
P粉727531237

The approach you took is correct, but you are right that the storage event does not fire in the same window/tab that caused the storage change. The storage event is intended to notify other windows or tabs that storage has been modified by a different window or tab.

In your case, since you are updating the localStorage value in the same window, the storage event will not be triggered and therefore the component you subscribe to will not receive the update.

To overcome this limitation, you can modify your custom hook to use a different mechanism to notify subscribing components about localStorage value changes. One approach is to use a separate event system (such as the React Context API or a state management library like Redux) to handle communication between components.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!