pmndrs / jotai

👻 Primitive and flexible state management for React
https://jotai.org
MIT License
18.25k stars 590 forks source link

atomWithStorage merge initial value #1316

Closed mwisnicki closed 2 years ago

mwisnicki commented 2 years ago

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.

dai-shi commented 2 years ago

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