Dependent signals
#560
|
How can dependent signals be implemented, where changes in one signal trigger updates in another, without causing a 'Cycle detected' error as encountered in the provided code snippet? import { signal, effect } from "@preact/signals-core";
const num = signal(0)
setInterval(() => {
num.value += 1
}, 1000)
const evenCounter = signal(0)
effect(() => {
if (num.value % 2) {
evenCounter.value += 1
}
})
effect(() => {
document.getElementById("app").innerHTML = evenCounter.value
})For example, such behavior could be used when a listener in one location is attached to one signal, triggering class methods that internally change another signal. So far, the only solution I have found to this problem is to move these methods out of the call stack using |
Answered by
Kanaye
Apr 14, 2024
Replies: 2 comments 1 reply
|
This seems like it could be applicable in this case. const counter = signal(0);
const effectCount = signal(0);
const fn = () => effectCount.value + 1;
effect(() => {
console.log(counter.value);
// Whenever this effect is triggered, run `fn` that gives new value
effectCount.value = untracked(fn);
}); |
0 replies
|
You'd normally just use |
1 reply
Answer selected by
kirrosh
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You'd normally just use
computedfor this.I updated your initial codesandbox to show one way how this could be implemented: https://codesandbox.io/p/sandbox/dependent-signals-forked-nq7p7v