Search code examples
sveltereactive-programmingsveltekit

Trigger $: when value is not used directly


I have this code in my svelte component:

$: {
    console.log(dateRange)
    formatDataForChart()
        .then(data => chartData = data);
}

I want to run FormatDataForChart() when dateRange is updated, but i dont actually do anything with dateRange in this segment (it is used in FormatDataForChart()). So if i were to remove the console.log here the $: would not run when dateRange is updated, is there a way for me to make sure it still runs without having a console.log or similar?

To clarify, the same code segment in react i would do like this:

useEffect(() => {
    formatDataForChart()
        .then(data => chartData = data);
}, [dateRange]);

The only way i can think of "using" dateRange here is by sending it as a parameter to FormatDataForChart(), but that also seems kinda dumb. I am new to Svelte and i just hope there is a better way to deal with this.


Solution

  • There are a few patterns to deal with this.

    One is using a sequence expression to list the required dependencies:

    $: dateRange, formatDataForChart().then(data => chartData = data);
    

    Another is to explicitly pass parameters, which will be a bit redundant as the variable would already be in scope.

    $: formatDataForChart(dateRange).then(data => chartData = data);
    

    What I would usually recommend (if possible), is defining the function reactively, that way any reactive calls will trigger when state within the function is changed:

    $: formatDataForChart = () => {
        // [use dateRange here]
    };
    $: formatDataForChart().then(data => chartData = data);
    

    (In Svelte 5 these workarounds will not be necessary, since the reactivity system can pass function and module boundaries.)