jotai icon indicating copy to clipboard operation
jotai copied to clipboard

atomWithStorage merge initial value

Open mwisnicki opened this issue 2 years ago • 1 comments

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.

mwisnicki avatar Jul 30 '22 21:07 mwisnicki

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...

dai-shi avatar Jul 31 '22 10:07 dai-shi