Skip to content

Commit

Permalink
atomWithUndo does not return the target value
Browse files Browse the repository at this point in the history
  • Loading branch information
dmaskasky committed Mar 5, 2024
1 parent 772acd8 commit dabbee6
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 15 deletions.
12 changes: 3 additions & 9 deletions src/atomWithHistory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,9 @@ import type { Atom } from 'jotai/vanilla'
* @returns an atom with an array of history states
*/
export function atomWithHistory<T>(targetAtom: Atom<T>, 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)
Expand Down
12 changes: 6 additions & 6 deletions src/atomWithUndo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export function atomWithUndo<T>(targetAtom: PrimitiveAtom<T>, 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
Expand All @@ -36,7 +36,7 @@ export function atomWithUndo<T>(targetAtom: PrimitiveAtom<T>, 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
Expand All @@ -45,7 +45,7 @@ export function atomWithUndo<T>(targetAtom: PrimitiveAtom<T>, limit: number) {
return null
},
(get) => {
get(refAtom).stack = [[get(targetAtom)]]
get(refAtom).stack = [get(targetAtom)]
return () => {
const ref = get(refAtom)
ref.index = 0
Expand Down Expand Up @@ -73,9 +73,9 @@ export function atomWithUndo<T>(targetAtom: PrimitiveAtom<T>, 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) {
Expand Down

0 comments on commit dabbee6

Please sign in to comment.