Add loading state for atomWithStorage #2369
Unanswered
christiearcus
asked this question in
Ideas
Replies: 2 comments 1 reply
-
I think we have a similar discussion before. Take a very simple example: const storage = {
...localStorage,
getItem(key) {
return localStorage.getItem(key) ?? "EMPTY VALUE"
},
}
const anAtom = atomWithStorage("foo", "DEFAULT VALUE", storage); If we need JSON: const EMPTY_DATA = { /* ... */ }
const DEFAULT_DATA = { /* ... */ }
const baseStorage = createJSONStorage();
const storage = {
...baseStorage,
getItem(key) {
return baseStorage.getItem(key, EMPTY_DATA)
},
}
const anAtom = atomWithStorage('foo', DEFAULT_DATA, storage) It might be worth considering adding // an idea
const anAtom = atomWithStorage('foo', DEFAULT_DATA, undefined, { emptyData: EMPTY_DATA }) |
Beta Was this translation helpful? Give feedback.
0 replies
-
Call it with const fooAtom = atomWithStorage('foo', 'bar', localStorage, { getOnInit: true }); This will load the value from storage when the atom gets initialized so components never see the initial value. |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I'm having a bit of trouble using
atomWithStorage
. It doesn't load synchronously as the first render is the initial value before re-rendering with the value from local storage. Because of this it's a bit hard to work with, and it'd be great to have a loading state so I know when it's ready to be used as with local storage there could be a value or undefined. It's be great to not just have the initial value persist.Could you let me know if there's a workaround for this?
Beta Was this translation helpful? Give feedback.
All reactions