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

useLocalStorage converts Infinity to null #247

Open
SteveVanOpstal opened this issue Oct 14, 2023 · 4 comments
Open

useLocalStorage converts Infinity to null #247

SteveVanOpstal opened this issue Oct 14, 2023 · 4 comments

Comments

@SteveVanOpstal
Copy link

const [number, setNumber] = useLocalStorage("number", Infinity);
console.log(number); // null

Seems to be related to JSON.stringify.

You can workaround this issue by not using Infinity but it would be nice to use this interface as you expect it.

@ngoue
Copy link

ngoue commented Oct 17, 2023

I disagree that this belongs here as an issue. This is exactly how the standard was defined to behave:

https://stackoverflow.com/questions/1423081/json-left-out-infinity-and-nan-json-status-in-ecmascript

@tylermcginnis
Copy link
Collaborator

Related: #253

@SteveVanOpstal
Copy link
Author

I disagree that this belongs here as an issue. This is exactly how the standard was defined to behave:

https://stackoverflow.com/questions/1423081/json-left-out-infinity-and-nan-json-status-in-ecmascript

It's not necessarily a software issue but coming across this I had the expectation, given that it's a blackbox function, that there were no restrictions. Only after looking at the source code I realised that it uses JSON.stringify to convert it to a string for localStorage, hence it is not able to handle Infinity and NaN. It might just come down to mentioning this in the docs.

@philg-ygt
Copy link

I agree with @SteveVanOpstal here: the use of JSON.stringify adds further constraints to the already existing constraints in place when using localStorage.setItem.

If, for example, you decide to send in an object and thus get [object Object] back, that's on you for not supplying a primitive, same as if you were using .setItem directly. It isn't the place of a hook to serialise input, particularly when there is no corresponding deserialising of the output; there is no JSON.parse wrapping localStorage.getItem in getLocalStorageItem...

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

4 participants