Skip to content

Commit

Permalink
Merge cc5289b into d1e0d0d
Browse files Browse the repository at this point in the history
  • Loading branch information
romgrk committed May 27, 2021
2 parents d1e0d0d + cc5289b commit aff11c7
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 2 deletions.
10 changes: 8 additions & 2 deletions packages/solid/src/reactive/signal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -237,9 +237,14 @@ export function createSelector<T, U>(

export function batch<T>(fn: () => T): T {
if (Pending) return fn();
const q: Signal<any>[] = (Pending = []),
let result;
const q: Signal<any>[] = Pending = [];
try {
result = fn();
Pending = null;
} finally {
Pending = null;
}

runUpdates(() => {
for (let i = 0; i < q.length; i += 1) {
const data = q[i];
Expand All @@ -250,6 +255,7 @@ export function batch<T>(fn: () => T): T {
}
}
}, false);

return result;
}

Expand Down
58 changes: 58 additions & 0 deletions packages/solid/test/signals.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
createDeferred,
createMemo,
createSelector,
batch,
untrack,
on,
onMount,
Expand Down Expand Up @@ -145,6 +146,63 @@ describe("Untrack signals", () => {
});
});

describe("Batch signals", () => {
test("Groups updates", done => {
createRoot(() => {
let count = 0;
const [a, setA] = createSignal(0);
const [b, setB] = createSignal(0);
createEffect(() => {
batch(() => {
setA(1);
setB(1);
});
});
createRenderEffect(() => {
count += 1;
});
createComputed(() => a() + b(), 0);
setTimeout(() => {
expect(count).toBe(1);
done();
});
});
});
test("Handles errors gracefully", done => {
createRoot(() => {
let error: Error;
let count = 0;
const [a, setA] = createSignal(0);
const [b, setB] = createSignal(0);
createEffect(() => {
try {
batch(() => {
setA(1);
throw new Error("test");
setB(1);
});
} catch(e) {
error = e
}
});
createRenderEffect(() => {
count += 1;
});
createComputed(() => a() + b(), 0);
setTimeout(() => {
expect(count).toBe(1);
expect(a()).toBe(1);
expect(b()).toBe(0);
setA(2);
expect(a()).toBe(2);
expect(error).toBeInstanceOf(Error);
expect(error.message).toBe("test");
done();
});
});
});
});

describe("Typecheck computed and effects", () => {
test("No default value can return undefined", () => {
createRoot(() => {
Expand Down

0 comments on commit aff11c7

Please sign in to comment.