Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can't properly serialize digit strings (or other strings that happen to be valid JSON) #84

Open
lynn opened this issue Feb 2, 2022 · 2 comments

Comments

@lynn
Copy link

lynn commented Feb 2, 2022

When I write

  const [x, setX] = useLocalStorage<string>("test", "");
  useEffect(() => setX("123456789123456789123"));
  console.log("x =", x);

I see x = 123456789123456800000 after refreshing the page.

This is because the value is identified as being JSON when reading it back out of LocalStorage, and then JSON.parse turns it into a float, with loss of precision.

In fact, x is now indeed a number, even though the type signature of useLocalStorage promises that it is string. 😱

Always converting JSON has other weird consequences:

  • You can type something like {"wow": "json injection"} into a useLocalStorage-backed text field and break stuff!
  • When serializing the word "true", it comes back out as a boolean value true.

It might be nice to have a useLocalStorageRaw that only works with strings and does not "helpfully" parse strings as JSON whenever it has the opportunity.

@jharrilim
Copy link
Collaborator

That is a really good point. It seems to come from this line:

storage.setItem(key, typeof value === 'object' ? JSON.stringify(value) : `${value}`);

I don't remember why this was done truthfully, but if we just did JSON.stringify on all values, it would avoid this problem

@iamsolankiamit
Copy link
Member

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants