useSessionStorage
does not store defaultValue
in session storage
#5230
Labels
Fix Unknown
It is not clear whether the can be resolved
What package has an issue?
@mantine/hooks
Describe the bug
When using
useSessionStorage
, thedefaultValue
is never initially saved to sessionStorage, leading to issues when trying to access it from outside the hook (see attached CodeSandbox link). Digging into the code, you can see why it's happening but it's unclear how to properly fix it without affecting the default behavior for others.The starting point is in this
useEffect
which would make it seem like it will set a default value if adefaultValue
prop is passed in and thevalue
is undefined:mantine/src/mantine-hooks/src/use-local-storage/create-storage.ts
Lines 145 to 149 in 59a4a7f
We are passing in a
defaultValue
that is notundefined
so that makes sense so far. But what aboutvalue
? We can see wherevalue
is set:mantine/src/mantine-hooks/src/use-local-storage/create-storage.ts
Line 106 in 59a4a7f
Looking into
readStorageValue
we see this function. Let's deal with it on a case by case basis:mantine/src/mantine-hooks/src/use-local-storage/create-storage.ts
Lines 82 to 104 in 59a4a7f
If
skipStorage
is set totrue
:storageBlockedOrSkipped
will evaluate totrue
return defaultValue as T;
which will not be nullvalue === undefined
on line 146 will be false, and it will notsetStorageValue
.If
skipStorage
is set tofalse
:storageBlockedOrSkipped
will in normal situations evaluate tofalse
const storageValue = getItem(key);
on line 100 will returnnull
return storageValue !== null ? deserialize(storageValue) : (defaultValue as T);
on line 101 will also return thedefaultValue
which will not benull
value === undefined
on line 146 will befalse
, and it will notsetStorageValue
.What version of @mantine/* packages do you have in package.json? (Note that all @mantine/* packages must have the same version in order to work correctly)
7.2.1
If possible, please include a link to a codesandbox with a minimal reproduction
https://codesandbox.io/s/festive-ptolemy-tw2dmr?file=/src/App.tsx
Do you know how to fix the issue
No
Do you want to send a pull request with a fix?
None
Possible fix
No response
The text was updated successfully, but these errors were encountered: