jotai
jotai copied to clipboard
atomWithStorage merge initial value
When using atomWithStorage
with large objects it's common to add new fields later in development.
Unfortunately even if I provide default value in initialValue
object this is ignored as initialValue
is only used when there is no data in storage.
It would be useful if atomWithStorage
accepted a flag or a function to merge initial and loaded state.
This sounds a valid point. We don't want to add features, but let developers to customize it as they like.
We can pass any storage
. For example, this should do.
import { atomWithStorage, createJSONStorage } from 'jotai/utils';
const createMyJsonStorage = (mergeState) => {
const storage = createJSONStorage(() => localStorage);
const getItem = (key) => {
const value = storage.getItem(key);
return { ...value, ...mergeState };
};
return { ...storage, getItem };
};
const anAtom = atomWithStorage('key', { foo: 123 }, createMyJsonStorage({ foo: 123 }));
I wonder if there are some better ways to abstract this as a util function. There would be many merge strategies...