Skip to content
Merged
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
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