Search code examples
javascriptchartschart.jsdataset

ChartJS : my labels is updated but not my data..?


It's me again. Still trying to get a chart on my webpage (I'm using WEBDEV). Here is more a javascript problem I think...

I create the chart with this function :

function creerGraph()
{
    const ctx = document.getElementById("myChart");
    
    const config = {
        type: 'pie',
        data: [],
        options: [],
        plugins: [] 
    };
    
    chart = new Chart(ctx, config);
}

And I add the data with this function where tabDonnees is a Structure table (2 members) :

function ajouteDonnees(tabDonnees)
{
    const colors = ['#fc5c65','#fd9644','#fed330','#26de81','#2bcbba','#45aaf2','#4b7bec','#a55eea','#778ca3'];
    
    for(var i = 0; i < tabDonnees.length; i++){
        chart.data.labels.push(tabDonnees[i].Libellé);
        
        chart.data.datasets.forEach((dataset)=> {
            dataset.data.push(tabDonnees[i].Nombre);        
            dataset.backgroundColor.push(colors[i]);
        });
    }

    chart.update();    
}

The chart is not visible but I'm pretty sure that it's because there's no data. When I check the console on my webpage, the labels are here, but the dataset is still empty. I already test this on another project and this worked really well, and I don't understand why it doesn't work on this project too...

I even try to do some change on my code like put the label and the value of data in a variable before the loop, but nothing change... (As expected, since it was doing the same thing...)


Solution

  • I Think your config variable structure should like this one:

    const config = {
        type: 'pie',
        data: {
            labels: [],
            datasets: [{
                data: [],
                backgroundColor: []
            }]
        },
        options: [],
        plugins: []
    };