UNPKG

jotai

Version:

👻 Next gen state management that will spook you

28 lines (23 loc) • 869 B
import { produce } from 'immer'; import { atom, useAtom } from 'jotai'; import { useCallback } from 'react'; /* eslint-disable import/named */ function atomWithImmer(initialValue) { const anAtom = atom(initialValue, (get, set, fn) => set(anAtom, produce(get(anAtom), draft => fn(draft)))); return anAtom; } /* eslint-disable import/named */ function useImmerAtom(anAtom) { const [state, setState] = useAtom(anAtom); const setStateWithImmer = useCallback(fn => { setState(produce(draft => fn(draft))); }, [setState]); return [state, setStateWithImmer]; } /* eslint-disable import/named */ function withImmer(anAtom) { const derivedAtom = atom(get => get(anAtom), (get, set, fn) => set(anAtom, produce(get(anAtom), draft => fn(draft)))); derivedAtom.scope = anAtom.scope; return derivedAtom; } export { atomWithImmer, useImmerAtom, withImmer };