Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: fixed useStateWithHistory issue with history state being a function after running history.back #2572

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions src/useStateWithHistory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,16 +30,17 @@ export function useStateWithHistory<S, I extends S>(
}

const isFirstMount = useFirstMountState();
const [state, innerSetState] = useState<S>(initialState as S);
const [state, innerSetState] = useState<S>(resolveHookState(initialState) as S);

const history = useRef<S[]>((initialHistory ?? []) as S[]);
const historyPosition = useRef(0);

// do the states manipulation only on first mount, no sense to load re-renders with useless calculations
if (isFirstMount) {
if (history.current.length) {
// if last element of history !== initial - push initial to history
if (history.current[history.current.length - 1] !== initialState) {
history.current.push(initialState as I);
if (history.current[history.current.length - 1] !== state) {
history.current.push(state as I);
}

// if initial history bigger that capacity - crop the first elements out
Expand All @@ -48,7 +49,7 @@ export function useStateWithHistory<S, I extends S>(
}
} else {
// initiate the history with initial state
history.current.push(initialState as I);
history.current.push(state);
}

historyPosition.current = history.current.length && history.current.length - 1;
Expand Down
6 changes: 6 additions & 0 deletions tests/useStateWithHistory.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,12 @@ describe('useStateWithHistory', () => {
});
expect(hook.result.current[0][0]).toBe(1);
});

it('should not contain function as initial state', () => {
let hook = getHook(() => 1, 3);

expect(hook.result.current[0][2].history[0]).toEqual(1);
});
});

describe('history.forward()', () => {
Expand Down