web icon indicating copy to clipboard operation
web copied to clipboard

useSessionStorageValue same key, different value

Open JaminFarr opened this issue 4 years ago • 2 comments

Prior Issues

I cannot see any related issues.

What is the current behavior?

Different instances of useSessionStorageValue with the same key that are mounted at the same can get out of sync when setValue is use on first mount within a useEffect. Only the component making the setValue call, and components before it, get the updated value. Components after do not update and have a stale value.

Steps to Reproduce

Using setValue in a useEffect(..., []).

const useStoredValue = () =>
  useSessionStorageValue("example-key", "Default Value");

const UpdateOnMount = () => {
  const [, setValue] = useStoredValue();

  useEffect(() => {
    setValue("Update Value");
  }, [setValue]);

  return null;
};

const DisplayValue = () => {
  const [value] = useStoredValue();

  return <p>Stored value is "{value}"</p>;
}

const App = () => (
  <div>
    <DisplayValue /> 
    <UpdateOnMount />
    <DisplayValue />
  </div>
)

codesandbox: https://codesandbox.io/s/eager-gould-ter7m?file=/src/App.js

The code above on first load displays:

Stored value is "Update Value"

Stored value is "Default Value"

Another codesandbox with random values and reset buttons: https://codesandbox.io/s/fervent-stitch-zqekk

There's a few work arounds:

  • Changing the component order
  • Using initializeWithStorageValue: false
  • Putting setValue in a setTimeout
  useEffect(() => {
    setTimeout(() => {
      setValue("Update Value");
     }, 0);
  }, [setValue]);

What is the expected behavior?

All instances of useSessionStorageValue with the same key should return the same value.

Environment Details

  • @react-hookz/web version: 12.0.0
  • react version: 17.0.2
  • react-dom version: 17.0.2
  • typescript version: N/A
  • OS: macOS BigSur
  • Browser: Chrome 95 / Firefox / Safari
  • Did this work in previous versions? No know

JaminFarr avatar Nov 12 '21 12:11 JaminFarr

:tada: This issue has been resolved in version 12.0.3 :tada:

The release is available on:

Your semantic-release bot :package::rocket:

xobotyi avatar Dec 23 '21 11:12 xobotyi

Well, nope, didnt worked out. Ill dig more later.

xobotyi avatar Dec 23 '21 11:12 xobotyi

I'm investigating this also. Will report here if I find anything out.

ArttuOll avatar Oct 08 '22 10:10 ArttuOll

I can confirm that:

  • This affects both useLocalStorage and useSessionStorage (which is not surprising, since both use useStorage under the hood).
  • This bug has been present since useLocalStorage and useSessionStorage were first added to this library.

ArttuOll avatar Oct 08 '22 12:10 ArttuOll

:tada: This issue has been resolved in version 17.0.0 :tada:

The release is available on:

Your semantic-release bot :package::rocket:

xobotyi avatar Nov 03 '22 13:11 xobotyi