dependenciessvelte

How to resolve concurrent dependency change?


So let's say I have these variables ($: marks a reactive statement, so when any of the values after = change, the variable is updated):

let x = 0;
$: y = x;
$: z = x + y;

function onSomeUserInteraction(input) {
   y = input;
}

So in this case, x is an independent variable, meanwhile y depends on x, and can also be altered by user interaction. And z depends on x and y.

Now my problem is, that when x changes, this triggers an update in z. But since y depends on x, it also changes, which triggers another, redundant update to z. So my question is, how can I handle these dependencies in such a way that changing x doesn't update z twice? The obvious solution would be just to have $: z = x + x. But the problem is with the user interaction, which might alter the value of y, so y may not always be equal to x.

Another way to reframe the code would be like this:

let x = 0;
$: y = x + i; // I is some arbitrary value that can be updated by the user
$: z = x + y;

Any suggestions for how to resolve this? Thank you.


Solution

  • You can declare your variable non-reactively and use a reactive effect to update your value where you explicitly tell Svelte what variable triggers the effect, like this:

    <script>
        let x = 0;
        $: y = x;
        let z = x + y;
    
        // If `y` changes, update `z`. 
        $: y, z = x + y;
        
      /* This way `x` doesn't update `z` directly, 
       instead it reactively updates `y` 
       which in turn triggers the `z` update */
        
        function onSomeUserInteraction(input) {
            y = input;
        }
    </script>