diff --git a/src/atomWithHistory.ts b/src/atomWithHistory.ts index 993adda..9ee41db 100644 --- a/src/atomWithHistory.ts +++ b/src/atomWithHistory.ts @@ -7,15 +7,9 @@ import type { Atom } from 'jotai/vanilla' * @returns an atom with an array of history states */ export function atomWithHistory(targetAtom: Atom, limit: number) { - const refAtom = atom( - () => ({ - history: [] as T[], - }), - (get) => () => { - get(refAtom).history.length = 0 - } - ) - refAtom.onMount = (mount) => mount() + const refAtom = atom(() => ({ + history: [] as T[], + })) refAtom.debugPrivate = true return atom((get) => { const ref = get(refAtom) diff --git a/src/atomWithUndo.ts b/src/atomWithUndo.ts index dd411d6..e48415e 100644 --- a/src/atomWithUndo.ts +++ b/src/atomWithUndo.ts @@ -21,7 +21,7 @@ export function atomWithUndo(targetAtom: PrimitiveAtom, limit: number) { type DoAction = typeof UNDO | typeof REDO const refAtom = atom(() => ({ index: 0, - stack: [] as T[][], + stack: [] as T[], action: null as DoAction | null, })) refAtom.debugPrivate = true @@ -36,7 +36,7 @@ export function atomWithUndo(targetAtom: PrimitiveAtom, limit: number) { // Remove future states if any ref.stack = ref.stack.slice(0, ref.index + 1) // Push the current state to the history - ref.stack.push(history.slice()) + ref.stack.push(history[0] as T) // Limit the history ref.stack = ref.stack.slice(-limit) // Move the current index to the end @@ -45,7 +45,7 @@ export function atomWithUndo(targetAtom: PrimitiveAtom, limit: number) { return null }, (get) => { - get(refAtom).stack = [[get(targetAtom)]] + get(refAtom).stack = [get(targetAtom)] return () => { const ref = get(refAtom) ref.index = 0 @@ -73,9 +73,9 @@ export function atomWithUndo(targetAtom: PrimitiveAtom, limit: number) { (get, set, update) => { const ref = get(refAtom) const setCurrentState = () => { - const currentSlice = ref.stack[ref.index] - if (currentSlice?.[0] === undefined) return - set(targetAtom, currentSlice[0]) + const value = ref.stack[ref.index] + if (value === undefined) return + set(targetAtom, value as T) } if (update === UNDO) { if (get(baseAtom).canUndo) {