Mat
Mat

Reputation: 77

Create multiple pie chart simultaneously using chart.js

I'm trying to create 3 Pie charts using chart.js library but each time it raises the following error:

TypeError: me.getDatasetMeta(...).controller is null

The way I create my charts is that I use a function called create_chart to override a config object and create a new chart instance. It works perfectly well with one chart but when it gets called repeatedly or even quickly by multiple clicks it raises the aforementioned error.

The html file is:

<div class="wrap_chart">
    <div class="wrap_chart_view">
        <canvas id="chart-area"></canvas>
    </div>
</div>
<div class="wrap_chart_sub">
    <div class="wrap_chart_sub_view">
        <canvas id="chart-area1"></canvas>
        <canvas id="chart-area2"></canvas>
        <canvas id="chart-area3"></canvas>
    </div>
</div>

The snippet that is responsible for function calls is:

var reg = meta[label]["regulation"];
var vc = meta[label]["vc"];
var msc = meta[label]["msc"];
if(Object.keys(vc).length != 0){
    create_chart(vc, "Variation Type", 2)
};
if(Object.keys(msc).length != 0){
    create_chart(msc, "Functional Consequence", 3)
};
if (Object.keys(reg).length != 0){
    create_chart(reg, "regulation", 1)

The error is raised when all the ifs evaluated as True.

And the create_chart function is the following:

function create_chart(obj, lbl, ind){
    var conf2 = Object.assign({}, config_x);
    var data = Object.values(obj);
    var labels = Object.keys(obj);
    //console.log(data);
    //console.log(labels);
    var cols = [];
    for(var i = 0; i< labels.length; i++) {
        cols.push(getRandomColor());
    }
    var dataset = [{
            data: data,
            backgroundColor: cols,
            label: lbl
        }]
    conf2.data.datasets = dataset;
    conf2.data.labels = labels;
    conf2.options.title.text = lbl;
    console.log(conf2);
    var canvas_x = document.getElementById('chart-area' + ind);
    var ctx2 = canvas_x.getContext('2d');
    new Chart(ctx2, conf2);

}

I used console to log everything and it seems that everything is fine. They only problem that I can think of is the way instantiation works at line Chart(ctx2, conf2);. I also check the doc and encountered the DatasetController bu couldn't use it in this case.

Chart.controllers.pie = Chart.DatasetController.extend({})

When I add this to my code it raises scale is undefined error.

Upvotes: 0

Views: 736

Answers (1)

Mat
Mat

Reputation: 77

Just solved the problem by calling a delay function before generating charts:

function sleep(ms) {
    return new Promise(create_chart => setTimeout(create_chart, ms));
}
async function demo() {
    await sleep(2000);
}

And in create_chart function:

demo();
new Chart(ctx2, config);

Upvotes: 1

Related Questions