Skip to content

Commit a800802

Browse files
committed
fix: correct nested batch behavior. Solves #217
1 parent e3ee594 commit a800802

File tree

2 files changed

+13
-5
lines changed

2 files changed

+13
-5
lines changed

src/utils/__tests__/batched-updates.test.js

+9-2
Original file line numberDiff line numberDiff line change
@@ -56,13 +56,20 @@ describe('batch', () => {
5656
const child = jest.fn().mockReturnValue(null);
5757
render(<TestComponent>{child}</TestComponent>);
5858
const update = child.mock.calls[0][0];
59-
act(() => update());
59+
act(() => {
60+
update();
61+
update();
62+
update();
63+
});
64+
65+
// nothing should be yet called
66+
expect(child.mock.calls[2]).toEqual(undefined);
6067

6168
// scheduler uses timeouts on non-browser envs
6269
await act(() => new Promise((r) => setTimeout(r, 10)));
6370

6471
// assertion no longer relevant with React 18+
65-
expect(child.mock.calls[2]).toEqual([expect.any(Function), 1, 1]);
72+
expect(child.mock.calls[2]).toEqual([expect.any(Function), 3, 1]);
6673

6774
supportsMock.mockRestore();
6875
});

src/utils/batched-updates.js

+4-3
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import {
88
import defaults from '../defaults';
99
import supports from './supported-features';
1010

11-
let isInsideBatchedSchedule = false;
11+
let isInsideBatchedSchedule = 0;
1212

1313
export function batch(fn) {
1414
// if we are in node/tests or nested schedule
@@ -20,11 +20,12 @@ export function batch(fn) {
2020
return unstable_batchedUpdates(fn);
2121
}
2222

23-
isInsideBatchedSchedule = true;
23+
isInsideBatchedSchedule = 0;
2424
// Use ImmediatePriority as it has -1ms timeout
2525
// https://github.com/facebook/react/blob/main/packages/scheduler/src/forks/Scheduler.js#L65
2626
return scheduleCallback(ImmediatePriority, function scheduleBatchedUpdates() {
27+
isInsideBatchedSchedule++
2728
unstable_batchedUpdates(fn);
28-
isInsideBatchedSchedule = false;
29+
isInsideBatchedSchedule--;
2930
});
3031
}

0 commit comments

Comments
 (0)