Chartjs-Reactivity Chartjs in Svelte

0👍

Looking at the Line Chart Example some imports from chart.js and ChartJS.register() seem to be necessary

The Line component from svelte-chartjs exports a reference to the chart on which .update() can be called after changing the data. The reference can be accessed via a local variable and bind:

Notice that clearInterval() takes the reference to the interval (and maybe change rendom to random as in Math.random())

REPL

<script>
    import {
        Chart as ChartJS,
        Title,
        Tooltip,
        Legend,
        LineElement,
        LinearScale,
        PointElement,
        CategoryScale,
    } from 'chart.js';

    ChartJS.register(
        Title,
        Tooltip,
        Legend,
        LineElement,
        LinearScale,
        PointElement,
        CategoryScale
    );

    import { Line } from "svelte-chartjs";
    import { onMount } from "svelte";

    let labels = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];
    let energy =[1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    
    let chartRef

    let data = {
        labels,
        datasets: [
            {
                label: "Dataset",
                data: energy,
                borderColor: "rgb(255, 99, 132)",
                backgroundColor: "rgba(255, 99, 132, 0.5)"
            },
        ]
    };

    onMount(() => {
        const interval = setInterval(() => {
            rendom();
        }, 1000);
        return () => {
            clearInterval(interval);
        };
    })

    function rendom() {
        let index=Math.round(Math.random()*9);
        energy[index]=Math.round(Math.random()*100)
        chartRef.update()
    }

</script>

<Line bind:chart={chartRef} data={data}/>

Leave a comment