score:1

this is a slightly different approach, but i think it's simpler than what you're doing:

stop using state

try passing arrays as parameters into your function, and then send the parameters directly to the chart data object, and then initiating the chart directly from inside the function (i avoid using react state in this case because it has a lag, and chart.js wants to initiate instantly).

here's a small example:

let barchart;
let newlabels = ["label1", "label2", "label3"];
let newdata = ["data1", "data2", "data3"];

createbarchart = (labels, data) => {

    let ctx = "bar_l1_chart";

    barchart = new chart(ctx, {
        type: 'horizontalbar',
        data: {
            labels: [labels],
            datasets: [{
                label: 'sentiment',
                data: [data],
            }]
        },
    });
};
this.createbarchart(newlabels, newdata);

now you just update the "newlabels" or "newdata" arrays, and re-call the function. a good way to do that is with react state managers, like:

componentwillrecieveprops(newprops){
     if(newprops.labels && newprops.data) {
          if(barchart){barchart.destroy()};
          this.createbarchart(newprops.labels, newprops.data)
     }
}

you will also need to "destroy()" the chart, before you recreate it. hopefully this is helpful!


Related Query

More Query from same tag