Skip to content

Commit 860e27e

Browse files
committed
fix: sync effect by default
1 parent 1f3b0dc commit 860e27e

File tree

2 files changed

+12
-18
lines changed

2 files changed

+12
-18
lines changed

src/core.ts

+6-12
Original file line numberDiff line numberDiff line change
@@ -29,20 +29,14 @@ unstable_replaceInternalFunction(
2929
},
3030
);
3131

32-
const callbackStack = [new Set<() => void>()];
33-
let callbackPromise: Promise<void> | undefined;
32+
const callbackStack: Set<() => void>[] = [];
3433

3534
const registerCallback = (callback: () => void) => {
36-
const callbacks = callbackStack[callbackStack.length - 1]!;
37-
callbacks.add(callback);
38-
if (!callbackPromise && callbackStack.length === 1) {
39-
callbackPromise = Promise.resolve().then(() => {
40-
callbackPromise = undefined;
41-
for (const callback of callbacks) {
42-
callback();
43-
}
44-
callbacks.clear();
45-
});
35+
if (callbackStack.length) {
36+
callbackStack[callbackStack.length - 1]!.add(callback);
37+
} else {
38+
// invoke immediately
39+
callback();
4640
}
4741
};
4842

tests/01_watch.spec.ts

+6-6
Original file line numberDiff line numberDiff line change
@@ -37,13 +37,10 @@ describe('watch', () => {
3737
});
3838
expect(data).toEqual([0]);
3939
++state.nested.count;
40-
await new Promise<void>((r) => setTimeout(r));
4140
expect(data).toEqual([0, 1]);
4241
++state.count;
43-
await new Promise<void>((r) => setTimeout(r));
4442
expect(data).toEqual([0, 1]);
4543
++state.nested.anotherCount;
46-
await new Promise<void>((r) => setTimeout(r));
4744
expect(data).toEqual([0, 1]);
4845
unwatch();
4946
});
@@ -59,16 +56,19 @@ describe('watch with batch', () => {
5956
expect(data).toEqual([0]);
6057
batch(() => {
6158
++state.count;
59+
++state.count;
6260
});
63-
expect(data).toEqual([0, 1]);
61+
expect(data).toEqual([0, 2]);
6462
batch(() => {
6563
++state.count;
64+
++state.count;
6665
});
67-
expect(data).toEqual([0, 1, 2]);
66+
expect(data).toEqual([0, 2, 4]);
6867
unwatch();
6968
batch(() => {
7069
++state.count;
70+
++state.count;
7171
});
72-
expect(data).toEqual([0, 1, 2]);
72+
expect(data).toEqual([0, 2, 4]);
7373
});
7474
});

0 commit comments

Comments
 (0)