Skip to content

Commit

Permalink
The computed error handler now sends the computed previous value as a…
Browse files Browse the repository at this point in the history
…n argument
  • Loading branch information
cesarParra committed Dec 6, 2024
1 parent a49874a commit 8998ac6
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
27 changes: 27 additions & 0 deletions src/lwc/signals/__tests__/computed.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,4 +128,31 @@ describe("computed values", () => {

expect(computed.value).toBe("fallback");
});

test("allows for custom error handlers to return the previous value", () => {
const signal = $signal(0);
function customErrorHandlerFn(_error: unknown, previousValue: number | undefined) {
return previousValue;
}

const computed = $computed(() => {
if (signal.value === 2) {
throw new Error("test");
}

return signal.value;
}, {
errorHandler: customErrorHandlerFn
});

expect(computed.value).toBe(0);

signal.value = 1;

expect(computed.value).toBe(1)

signal.value = 2;

expect(computed.value).toBe(1);
});
});
9 changes: 7 additions & 2 deletions src/lwc/signals/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export type Signal<T> = {
set value(newValue: T);
readOnly: ReadOnlySignal<T>;
brand: symbol;
peek(): T;
};

const context: VoidFunction[] = [];
Expand Down Expand Up @@ -105,7 +106,7 @@ function handleEffectError(error: unknown, props: EffectProps) {
type ComputedFunction<T> = () => T;
type ComputedProps<T> = {
identifier: string | null;
errorHandler?: (error: unknown) => T | undefined;
errorHandler?: (error: unknown, previousValue: T | undefined) => T | undefined;
};

/**
Expand Down Expand Up @@ -139,7 +140,8 @@ function $computed<T>(
try {
computedSignal.value = fn();
} catch (error) {
computedSignal.value = props.errorHandler(error);
const previousValue = computedSignal.peek();
computedSignal.value = props.errorHandler(error, previousValue);
}
} else {
// Otherwise, the error handling is done in the $effect
Expand Down Expand Up @@ -306,6 +308,9 @@ function $signal<T>(
get value() {
return getter();
}
},
peek() {
return _storageOption.get();
}
};

Expand Down

0 comments on commit 8998ac6

Please sign in to comment.