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: useStateWithHistory add two history in single value assignment #2527

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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
38 changes: 27 additions & 11 deletions src/useStateWithHistory.ts
Expand Up @@ -54,24 +54,40 @@ export function useStateWithHistory<S, I extends S>(
historyPosition.current = history.current.length && history.current.length - 1;
}

function once<T extends any[]>(fn: (...args: T) => void): (...args: T) => void {
let called = false;
let result: ReturnType<typeof fn>;

return function(...args: T): void {
if (!called) {
called = true;
result = fn.apply(null, args);
}
return result;
};
}

const setState = useCallback(
(newState: IHookStateSetAction<S>): void => {
const setStateSideEffect = once(() => {
// if current position is not the last - pop element to the right
if (historyPosition.current < history.current.length - 1) {
history.current = history.current.slice(0, historyPosition.current + 1);
}

historyPosition.current = history.current.push(newState as I) - 1;

// if capacity is reached - shift first elements
if (history.current.length > capacity) {
history.current = history.current.slice(history.current.length - capacity);
}
})
innerSetState((currentState) => {
newState = resolveHookState(newState, currentState);

// is state has changed
if (newState !== currentState) {
// if current position is not the last - pop element to the right
if (historyPosition.current < history.current.length - 1) {
history.current = history.current.slice(0, historyPosition.current + 1);
}

historyPosition.current = history.current.push(newState as I) - 1;

// if capacity is reached - shift first elements
if (history.current.length > capacity) {
history.current = history.current.slice(history.current.length - capacity);
}
setStateSideEffect()
}

return newState;
Expand Down