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!
- [Chartjs]-Draw horizontal line on chart in chart.js on v2
- [Chartjs]-Error with Chart.js : TypeError: t is undefined
Source:stackexchange.com