react-hookz / web

React hooks done right, for browser and SSR.
https://react-hookz.github.io/web/
MIT License
1.89k stars 93 forks source link

Removal of localStorage or sessionStorage key is not synced across tabs #1545

Open develohpanda opened 5 months ago

develohpanda commented 5 months ago

Prior Issues

None that I could find

What is the current behavior?

Remove a local storage key in one tab, observe that it does not trigger an update in another tab.

Steps to Reproduce

  1. Open the storybook example in two tabs https://react-hookz.github.io/web/?path=/docs/side-effect-uselocalstoragevalue--example
  2. Edit the value in one tab, notice that it updates in the other tab
  3. Press the "remove storgae value" button in one tab, notice that it does not update in the other tab

What is the expected behavior?

Key removals should be synchronized across tabs

Potential cause

I believe the cause is in this event handler, specifically the evt.newValue condition. https://github.com/react-hookz/web/blob/579a445fcc9f4f4bb5b9d5e670b2e57448b4ee50/src/useStorageValue/index.ts#L28-L32

When a key is removed, evt.newValue is set to null, and thus gets filtered out in this conditional. I have confirmed through while debugging, and the second tab does receive the storage event correctly, but gets filtered out here.

This seems like a bug, because there's an invocation to the event handlers with the value null on the during the remove step, however that only applies to the current tab and is not synced to other tabs.

https://github.com/react-hookz/web/blob/579a445fcc9f4f4bb5b9d5e670b2e57448b4ee50/src/useStorageValue/index.ts#L235

Environment Details