Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Issue with @signal's cache: computed instances sharing the same cache #92

Merged
merged 1 commit into from
Dec 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,15 +111,23 @@ function computedDecorator<Value = any>(
throw new Error(`Can only use @cached on getters.`);
}

let caches = new WeakMap<typeof target, Signal.Computed<Value>>();
const caches = new WeakMap<
typeof target,
WeakMap<object, Signal.Computed<Value>>
>();

return function (this: unknown) {
let cache = caches.get(target);
if (!cache) {
cache = new Signal.Computed(() => target.call(this));
cache = new WeakMap();
caches.set(target, cache);
}
let effect = cache.get(this as object);
if (!effect) {
effect = new Signal.Computed(() => target.call(this));
cache.set(this as object, effect);
}

return cache.get();
return effect.get();
};
}
21 changes: 21 additions & 0 deletions tests/@signal.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,4 +83,25 @@ describe("@signal (getter)", () => {
new State();
}, /@signal can only be used on accessors or getters/);
});

it("not shared between instances", () => {
class State {
@signal accessor #value = 3;

@signal
get doubled() {
return this.#value * 2;
}

constructor(value: number) {
this.#value = value;
}
}

let state1 = new State(1);
let state2 = new State(2);

assert.strictEqual(state1.doubled, 2);
assert.strictEqual(state2.doubled, 4);
});
});
Loading