In my component I have 3 variables where value2 depends on value1 and value3 depends on value2. When I update value1 then value2 gets updated but value3 stays the same. I am new to Svelte. Is this behavior somewhere documented?
Playground: https://svelte.dev/repl/c092a060a12641489d81e2c5857473bf?version=3.50.1
<script>
let value1 = 0;
let value2 = 0;
let value3 = 0;
function updateValue3(value) {
value3 = value;
}
$: updateValue3(value2);
function updateValue2(value) {
// uncomment this to make it working
// setTimeout(() => {
// value2 = value;
// });
value2 = value;
}
$: updateValue2(value1);
</script>
<button on:click={() => value1++}>increment</button>
<h1>value1: {value1}, value2: {value2}, value3: {value3}</h1>
>Solution :
You can fix it by ordering the reactive statements differently.
$: updateValue2(value1);
$: updateValue3(value2);
Svelte is supposed to order dependencies automatically, but because the assignment is "hidden" inside the function, the dependency is unknown to the Svelte compiler, so you have to fix the order manually.
If you have no functions and assign directly, the order will not matter:
$: value3 = value2;
$: value2 = value1;
The fixed order generates this update code:
$$self.$$.update = () => {
if ($$self.$$.dirty & /*value1*/ 1) {
$: updateValue2(value1);
}
if ($$self.$$.dirty & /*value2*/ 2) {
$: updateValue3(value2);
}
};
The original code generates this:
$$self.$$.update = () => {
if ($$self.$$.dirty & /*value2*/ 2) {
$: updateValue3(value2);
}
if ($$self.$$.dirty & /*value1*/ 1) {
$: updateValue2(value1);
}
};
The dirty flags are then reset every update and the first condition is never true.