0

I am having trouble with reactivity Chartjs in Svelte. I wish that chart update eminently when the data for energy changes. What is missing in this code ?

<script lang="ts">
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 data = {
    labels,
    datasets: [
        {
            label: "Dataset",
            data: energy,
            borderColor: "rgb(255, 99, 132)",
            backgroundColor: "rgba(255, 99, 132, 0.5)"
        },
    ]
};

$:labels,energy,data

onMount(() => {
    const interval = setInterval(() => {
        rendom();
        console.log(energy)
    }, 1000);
    return () => {
      clearInterval(1);
    };
})
    

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

</script>

<Line data={data}/>

Answers for my problem.

enval
  • 3
  • 2

1 Answers1

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}/>
Corrl
  • 6,206
  • 1
  • 10
  • 36