useLocalStorageHook set defaultValue to undefined but get empty string
See original GitHub issueWhat package has an issue
Describe the bug
Hello, why choose Nullish coalescing operator to make defaultValue which is undefined or null to empty string in useLocalStorageHook?
It’s a little weird if I expect an undefined/null defaultValue but get an empty string.
Also, is there a typo here in use-local-storage?
If set to true, value will be update is useEffect after mount
If set to true, value will be update in useEffect after mount
What version of @mantine/hooks page do you have in package.json?
latest
If possible, please include a link to a codesandbox with the reproduced problem
https://codesandbox.io/s/kind-star-v25pry?file=/src/App.tsx
Do you know how to fix the issue
Yes
Are you willing to participate in fixing this issue and create a pull request with the fix
Yes
Possible fix
const readStorageValue = useCallback(
(skipStorage?: boolean): T => {
if (typeof window === 'undefined' || !(type in window) || skipStorage) {
return defaultValue as T;
// return (defaultValue ?? '') as T;
}
const storageValue = window[type].getItem(key);
return storageValue !== null ? deserialize(storageValue) : (defaultValue as T);
// return storageValue !== null ? deserialize(storageValue) : ((defaultValue ?? '') as T);
},
[key, defaultValue]
);
Issue Analytics
- State:
- Created a year ago
- Reactions:1
- Comments:10 (10 by maintainers)
Top Results From Across the Web
Specify default value for HTML5 Local Storage item?
Only works if you never save empty strings OR booleans OR if your variable can be 0. Solution which is longer but always...
Read more >Using localStorage with React Hooks - LogRocket Blog
After importing the custom Hook, we can use it and pass along the unique key and the default value, which, in this case,...
Read more >[v5.6.1-beta.2] DefaultValues empty string gives undefined
Describe the bug When using defaultValues and default value is "", Controller sets value to undefined which converts input to uncontrolled.
Read more >use-local-storage | Mantine
Value is set both to state and localStorage at 'color-scheme'. setValue('light'); ... parse localStorage string value and return value */.
Read more >useLocalStorage React Hook - useHooks
Since the local storage API isn't available in server-rendering environments, we check that typeof window !== "undefined" to make SSR and SSG work...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
I’m fine with this, feel free to create a PR
I created #2872.