Skip to content

Commit

Permalink
fix: correct nested batch behavior. Solves #217
Browse files Browse the repository at this point in the history
  • Loading branch information
theKashey committed Nov 17, 2023
1 parent e3ee594 commit a800802
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 5 deletions.
11 changes: 9 additions & 2 deletions src/utils/__tests__/batched-updates.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,13 +56,20 @@ describe('batch', () => {
const child = jest.fn().mockReturnValue(null);
render(<TestComponent>{child}</TestComponent>);
const update = child.mock.calls[0][0];
act(() => update());
act(() => {
update();

Check warning on line 60 in src/utils/__tests__/batched-updates.test.js

View workflow job for this annotation

GitHub Actions / build (12.x)

Delete `··`
update();

Check warning on line 61 in src/utils/__tests__/batched-updates.test.js

View workflow job for this annotation

GitHub Actions / build (12.x)

Delete `··`
update();

Check warning on line 62 in src/utils/__tests__/batched-updates.test.js

View workflow job for this annotation

GitHub Actions / build (12.x)

Delete `··`
});

// nothing should be yet called
expect(child.mock.calls[2]).toEqual(undefined);

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

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

supportsMock.mockRestore();
});
Expand Down
7 changes: 4 additions & 3 deletions src/utils/batched-updates.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
import defaults from '../defaults';
import supports from './supported-features';

let isInsideBatchedSchedule = false;
let isInsideBatchedSchedule = 0;

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

isInsideBatchedSchedule = true;
isInsideBatchedSchedule = 0;
// Use ImmediatePriority as it has -1ms timeout
// https://github.com/facebook/react/blob/main/packages/scheduler/src/forks/Scheduler.js#L65
return scheduleCallback(ImmediatePriority, function scheduleBatchedUpdates() {
isInsideBatchedSchedule++

Check warning on line 27 in src/utils/batched-updates.js

View workflow job for this annotation

GitHub Actions / build (12.x)

Insert `;`
unstable_batchedUpdates(fn);
isInsideBatchedSchedule = false;
isInsideBatchedSchedule--;
});
}

0 comments on commit a800802

Please sign in to comment.