himynameisdave / svelte-frappe-charts

📈 Svelte bindings for frappe-charts.
https://frappe.io/charts
MIT License
306 stars 16 forks source link

Update chart after props change #26

Closed simonh1000 closed 3 years ago

simonh1000 commented 3 years ago

I'm new to svelte so I may be missing something. I have code like this

    let reducedData = regionalData.reduce(foldfn, {});
    let vals = Object.values(reducedData);
    let datasets = [];
    let data = {
        labels: [],
        datasets,
    };

    afterUpdate(() => {
        datasets = selectedRegions.map((item) => {
            const fqn = item[0] + "-" + item[1];
            return { name: item[1], values: vals.map((r) => r[fqn]) };
        });
        data = {
            labels: Object.keys(reducedData),
            datasets,
        };
        if (chartRef) chartRef.update(data);
    });
</script>

    <Chart
        type="line"
        height="500"
        {data}
        {lineOptions}
        {axisOptions}
        bind:this={chartRef} />

selectedRegions is set by the props and can change. But although I see data changing (use @debug) the chart does not redraw.

I noticed that you add bind:this={chartRef} through the examples when they are supposed to be updatable, and use chartRef in the example. But the use of chartRef is missing in the update all example. It seemed as though .update should have worked but I am getting TypeError: chartRef.update is not a function

himynameisdave commented 3 years ago

I believe there may be some confusion in the documentation about what chartRef actually is. It is not the chart constructed by calling new frappe.Chart, but instead is a Svelte component binding (using this):

image

Note that you shouldn't need to add that afterUpdate call at all, because this component already does that when the props update. So as far as I can tell, your issue might be with how you're using Svelte here. I think by making your selectedRegions a reactive declaration (and/or perhaps some other variables in your code), you might be able to have this working like you expect. This library reacts to prop changes though, so I would expect your charts to redraw on prop changes.

In any case, I don't think this is an issue with svelte-frappe-charts, so I will close this for now, but I am happy to re-open if you have any more info or think there is indeed a bug in this library! 👍