Skip to content

Commit

Permalink
fix: Computed values that return the unchanged value of a tracked sig…
Browse files Browse the repository at this point in the history
…nal are now recomputed when the source signal changes.
  • Loading branch information
cesarParra committed Dec 4, 2024
1 parent 33c46ea commit 100308e
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 4 deletions.
13 changes: 12 additions & 1 deletion src/lwc/signals/__tests__/computed.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { $computed, $signal } from "../core";
import { $computed, $effect, $signal } from "../core";

describe("computed values", () => {
test("can be created from a source signal", () => {
Expand Down Expand Up @@ -46,4 +46,15 @@ describe("computed values", () => {
expect(computed.value).toBe(2);
expect(anotherComputed.value).toBe(4);
});

test("computed objects that return the same value as a tracked signal recomputes", () => {
const signal = $signal({ a: 0, b: 0 }, { track: true });
const computed = $computed(() => signal.value);
const spy = jest.fn(() => computed.value);
$effect(spy);
spy.mockReset();

signal.value.a = 1;
expect(spy).toHaveBeenCalled();
});
});
19 changes: 16 additions & 3 deletions src/lwc/signals/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ function $effect(fn: VoidFunction): void {
const effectNode: EffectNode = {
error: null,
state: UNSET
}
};

const execute = () => {
if (effectNode.state === COMPUTING) {
Expand Down Expand Up @@ -107,7 +107,7 @@ function computedGetter<T>(node: ComputedNode<T>) {
*/
function $computed<T>(fn: ComputedFunction<T>): ReadOnlySignal<T> {
const computedNode: ComputedNode<T> = {
signal: $signal<T | undefined>(undefined),
signal: $signal<T | undefined>(undefined, { track: true }),
error: null,
state: UNSET
};
Expand Down Expand Up @@ -143,6 +143,8 @@ interface TrackableState<T> {
get(): T;

set(value: T): void;

forceUpdate(): boolean;
}

class UntrackedState<T> implements TrackableState<T> {
Expand All @@ -159,6 +161,10 @@ class UntrackedState<T> implements TrackableState<T> {
set(value: T) {
this._value = value;
}

forceUpdate() {
return false;
}
}

class TrackedState<T> implements TrackableState<T> {
Expand All @@ -181,6 +187,10 @@ class TrackedState<T> implements TrackableState<T> {
set(value: T) {
this._value = this._membrane.getProxy(value);
}

forceUpdate(): boolean {
return true;
}
}

/**
Expand Down Expand Up @@ -232,7 +242,10 @@ function $signal<T>(
}

function setter(newValue: T) {
if (isEqual(newValue, _storageOption.get())) {
if (
!trackableState.forceUpdate() &&
isEqual(newValue, _storageOption.get())
) {
return;
}
trackableState.set(newValue);
Expand Down

0 comments on commit 100308e

Please sign in to comment.