UNPKG

jotai-history

Version:
30 lines • 1.01 kB
import { atom } from 'jotai/vanilla'; import { RESET } from './actions.js'; /** * @param targetAtom an atom or derived atom * @param limit the maximum number of history states to keep * @returns an atom with an array of history states */ export function withHistory(targetAtom, limit) { const refreshAtom = atom(0); refreshAtom.debugPrivate = true; const historyAtom = { read: (get) => (get(refreshAtom), { history: [] }), write: (get, set) => { get(historyAtom).history.length = 0; set(refreshAtom, (v) => v + 1); }, onMount: (reset) => reset, debugPrivate: true, init: 1, // dirty hack to bypass hasInitialValue }; return atom((get) => { const ref = get(historyAtom); return (ref.history = [get(targetAtom), ...ref.history].slice(0, limit)); }, (_, set, action) => { if (action === RESET) { set(historyAtom); } }); } //# sourceMappingURL=withHistory.js.map