Skip to content

Commit

Permalink
fix(history): fix getHistory issue
Browse files Browse the repository at this point in the history
  • Loading branch information
unadlib committed Mar 18, 2024
1 parent 4572247 commit e08765d
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 14 deletions.
10 changes: 4 additions & 6 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,21 +144,19 @@ export const useTravel = <S, A extends boolean, F extends boolean>(
currentState as object,
allPatches.patches[i]
) as S;
console.log('i', i, JSON.stringify(currentState));
history.push(currentState);
}
currentState = state as any;
const inversePatches = allPatches.inversePatches;
const stateIndex =
inversePatches.length === cachedPosition
? inversePatches.length - 1
: inversePatches.length - cachedPosition - 1;
for (let i = stateIndex; i > -1; i--) {
for (let i = cachedPosition - 1; i > -1; i--) {
currentState = apply(
currentState as object,
allPatches.inversePatches[i]
) as S;
console.log('j', i, JSON.stringify(currentState));
history.unshift(currentState);
}
console.log('history', JSON.stringify(history));
return history;
},
patches: allPatches,
Expand Down
64 changes: 56 additions & 8 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,13 +130,13 @@ describe('useTravel', () => {
[nextState, setState, controls] = result.current;

act(() =>
setState((draft) => {
draft.todos.push({
name: 'todo 5',
});
})
);
[nextState, setState, controls] = result.current;
setState((draft) => {
draft.todos.push({
name: 'todo 5',
});
})
);
[nextState, setState, controls] = result.current;

expect(nextState).toEqual({
todos: [
Expand All @@ -154,7 +154,55 @@ describe('useTravel', () => {
},
],
});
console.log(controls.patches.patches.length, 'CCCC');

expect(controls.getHistory()).toEqual([
{
todos: [],
},
{
todos: [
{
name: 'todo 1',
},
{
name: 'todo 2',
},
],
},
{
todos: [
{
name: 'todo 1',
},
{
name: 'todo 2',
},
{
name: 'todo 4',
},
],
},
{
todos: [
{
name: 'todo 1',
},
{
name: 'todo 2',
},
{
name: 'todo 4',
},
{
name: 'todo 5',
},
],
},
]);

act(() => controls.go(1));
[nextState, setState, controls] = result.current;

expect(controls.getHistory()).toEqual([
{
todos: [],
Expand Down

0 comments on commit e08765d

Please sign in to comment.