Skip to content

Commit

Permalink
fix: sync effect by default (#1)
Browse files Browse the repository at this point in the history
  • Loading branch information
dai-shi authored Nov 22, 2024
1 parent 1f3b0dc commit 5495225
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 18 deletions.
18 changes: 6 additions & 12 deletions src/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,20 +29,14 @@ unstable_replaceInternalFunction(
},
);

const callbackStack = [new Set<() => void>()];
let callbackPromise: Promise<void> | undefined;
const callbackStack: Set<() => void>[] = [];

const registerCallback = (callback: () => void) => {
const callbacks = callbackStack[callbackStack.length - 1]!;
callbacks.add(callback);
if (!callbackPromise && callbackStack.length === 1) {
callbackPromise = Promise.resolve().then(() => {
callbackPromise = undefined;
for (const callback of callbacks) {
callback();
}
callbacks.clear();
});
if (callbackStack.length) {
callbackStack[callbackStack.length - 1]!.add(callback);
} else {
// invoke immediately
callback();
}
};

Expand Down
12 changes: 6 additions & 6 deletions tests/01_watch.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,10 @@ describe('watch', () => {
});
expect(data).toEqual([0]);
++state.nested.count;
await new Promise<void>((r) => setTimeout(r));
expect(data).toEqual([0, 1]);
++state.count;
await new Promise<void>((r) => setTimeout(r));
expect(data).toEqual([0, 1]);
++state.nested.anotherCount;
await new Promise<void>((r) => setTimeout(r));
expect(data).toEqual([0, 1]);
unwatch();
});
Expand All @@ -59,16 +56,19 @@ describe('watch with batch', () => {
expect(data).toEqual([0]);
batch(() => {
++state.count;
++state.count;
});
expect(data).toEqual([0, 1]);
expect(data).toEqual([0, 2]);
batch(() => {
++state.count;
++state.count;
});
expect(data).toEqual([0, 1, 2]);
expect(data).toEqual([0, 2, 4]);
unwatch();
batch(() => {
++state.count;
++state.count;
});
expect(data).toEqual([0, 1, 2]);
expect(data).toEqual([0, 2, 4]);
});
});

0 comments on commit 5495225

Please sign in to comment.