$effect
not running in this case
#14517
-
so I've this code: <script lang="ts">
let {
speed = 1,
...
}: Props = $props();
let dotLottie: DotLottie | undefined = $state();
$effect(() => { // this effect is not running whenever `speed` changes
if (dotLottie && dotLottie.isLoaded && typeof speed == 'number') {
dotLottie.setSpeed(speed);
}
});
$inspect(speed); // this logs every changes to `speed`
</script> but if i add a reference like: $effect(() => {
console.log(speed); // now effect runs because of this
if (dotLottie && dotLottie.isLoaded && typeof speed == 'number') {
dotLottie.setSpeed(speed);
}
});
</script> any idea why its not working in the first code? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Dependencies are captured at effect run-time and
If See also this issue for more context: As a workaround, you can switch around the order of the operators and move the speed check to the front if you don't need the effect to retrigger when |
Beta Was this translation helpful? Give feedback.
Dependencies are captured at effect run-time and
speed
is not used when the effect runs initially.dotLottie.isLoaded
is probably not reactive and the&&
causestypeof speed
to never be evaluated here since this is a short circuit logical operator (if the left side is falsy, the right side is skipped).If
isLoaded
were reactive and changed totrue
, this would work since then the entire if condition would be evaluated. If theDotLottie
object is a third party class, you may have to add some additional logic to re-trigger the$effect
on load.See also this issue for more context:
As a workaround, you can switch around the order of the operators and move the speed check to the front…