'chart.js - dynamically added chart makes previous ones disappear

Basically

Whenever I call addData like

addData("TEST1", 1);

or

addData("TEST2", 1);

then I'm checking whether chart named "TEST1" already exists and if it does then I return chart object and if it doesn't then I create new

and then I insert data on it

and it works to the point that when I create e.g 2nd chart, then first one disappears

but why?

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.min.js" integrity="sha512-QSkVNOCYLtj73J4hbmVoOV6KVZuMluZlioC+trLpewV8qMjsWqlIQvkn1KGX2StWvPMdWGBqim1xlC8krl1EKQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<div id="charts">

</div>


<script>
var dict = new Object();

function addData(name, data) 
{
    var chart = dict[name];
    if (chart == undefined)
    {
        console.log("adding chart:"  + name);
        chart = AddChart(name);
    }
    else
    {
        console.log("skipping chart creation:"  + name);
    }
        
    chart.data.labels.push(new Date().toLocaleTimeString());
    chart.data.datasets.forEach((dataset) => 
    {
        dataset.data.push(data);
    });
    chart.update();
}


function AddChart(name)
{
    const data = 
    {
        labels: [],
        datasets: [{
            label: name,
            backgroundColor: 'rgb(255, 99, 132)',
            borderColor: 'rgb(255, 99, 132)',
            data: [],
        }]
    };

    const config = 
    {
        type: 'line',
        data: data,
        options:
        {
            responsive: false,
            maintainAspectRatio: false,
        }
    };

    var cont = document.getElementById("charts");
    cont.innerHTML += `<div width="140px" height="140px"><canvas id="chart_${name}"></canvas></div>`;

    const myChart = new Chart
    (
        document.getElementById(`chart_${name}`).getContext('2d'),
        config
    );

    dict[name] = myChart;

    console.log("added");
    console.log(dict);
    return dict[name];
}

addData("TEST1", 1);
addData("TEST2", 1);
</script>


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source