UNPKG

jotai

Version:

👻 Primitive and flexible state management for React

23 lines (22 loc) • 749 B
import { atom } from '../../vanilla.js'; import { RESET } from './constants.js'; export function atomWithDefault(getDefault) { const EMPTY = Symbol(); const overwrittenAtom = atom(EMPTY); if (process.env.NODE_ENV !== 'production') { overwrittenAtom.debugPrivate = true; } const anAtom = atom((get, options) => { const overwritten = get(overwrittenAtom); if (overwritten !== EMPTY) { return overwritten; } return getDefault(get, options); }, (get, set, update) => { const newValue = typeof update === 'function' ? update(get(anAtom)) : update; set(overwrittenAtom, newValue === RESET ? EMPTY : newValue); }); return anAtom; }