react-use-storage icon indicating copy to clipboard operation
react-use-storage copied to clipboard

State updates on external storage changes not working

Open niklas-e opened this issue 6 years ago • 2 comments

useLocalStorage does not update the component state when the value in localStorage is changed from elsewhere. E.g. if I set the value via browser's devtools console. Tested on Chrome and Firefox.

Edit: Currently using react-use-storage version 0.4.0

niklas-e avatar Oct 11 '19 08:10 niklas-e

I think it could be fixed by using a simple event listener (window.addEventlistener('storage', () => {/* do magic */})). However, by default storage events are not fired in the same window where the change occurs, but it could be handled by dispatching the event on window object programmatically.

I could create a pull request if you think this is a valid solution.

niklas-e avatar Oct 11 '19 09:10 niklas-e

@niklas-e Another way to implement this would be to proxy all state changes. This would not work well with independent code fiddling with the storage, but if you have control on the storage keys that you care about, it may be better than modifying the intended behavior of the storage event.

I am not quite sure why the storage event was designed this way. Is it to avoid infinite event cascades in certain use cases? Is it to stay close to other existing APIs?