Skip to content

Commit

Permalink
fix(hook): sequential updater calls operate on latest state (#7)
Browse files Browse the repository at this point in the history
  • Loading branch information
YellowKirby authored Apr 12, 2024
1 parent 39c0959 commit d6acbb6
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 7 deletions.
13 changes: 6 additions & 7 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,13 +81,12 @@ function useMutative<
return options?.enablePatches ? [initialState, [], []] : initialState;
});
const updateState = useCallback((updater: any) => {
const currentState = options?.enablePatches ? state[0] : state;
if (typeof updater === 'function') {
setState(create(currentState, updater, options));
} else {
setState(create(currentState, () => updater, options));
}
}, [state]);
setState((latest: any) => {
const currentState = options?.enablePatches ? latest[0] : latest;
const updaterFn = typeof updater === 'function' ? updater : () => updater;
return create(currentState, updaterFn, options);
});
}, []);
return (
options?.enablePatches
? [state[0], updateState, state[1], state[2]]
Expand Down
21 changes: 21 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,27 @@ describe('useMutative', () => {
expect(state2).toEqual({ items: [1, 2] });
});

it('[useMutative] with multiple updates', () => {
const { result } = renderHook(() =>
useMutative({
items: [1],
})
);

const [state, setState] = result.current;
act(() => {
setState((draft) => {
draft.items.push(2);
});

setState((draft) => {
draft.items.push(3);
});
});
const [nextState] = result.current;
expect(nextState).toEqual({ items: [1, 2, 3] });
});

it('[useMutative] with patches', () => {
const { result } = renderHook(() =>
useMutative(
Expand Down

0 comments on commit d6acbb6

Please sign in to comment.