You are right, using the .update()
function is the correct way to do this. I just answered the question on the other one you referenced but wanted to provide it here as well.
No need to delete the existing chart or do something like removing the canvas element to later append a new one. That works.. but isn't necessary.
Working CodePen: https://codepen.io/vpolston/pen/KKRoEBY
Video walkthrough: https://www.youtube.com/watch?v=Ac5pzmHO3_A
Firstly if you want to know the why then I would recommend doing a console.log(myChart)
of your chart object. You'll see all kinds of properties that can be updated by simply assigning it a new value and then calling the myChart.update()
on your chart.
Let's say you have a chart that you called myChart when you instantiated it.. this part:
const myChart = new Chart('myChart', {}
The variable name is important. To update the dataset you silo down into what you saw when you console.log'd the chart. So your dataset would be
myChart.config.data.datasets[0].data
Just assign that a new value like this:
const newDatasArray = [1,52,23,23,48];
myChart.config.data.datasets[0].data = newDatasArray;
and then for the labels if you needed to change those:
const newLabelsArray = ["Jan", "Feb", "Mar", "Apr", "May"];
myChart.config.data.labels = newLabelsArray;
And then finally call the update function with myChart.update();
You'll see the chart update to use the new dataset and/or labels.
Hopefully that gives a bit more insight into properly updating a chart. If you have a further question let me know and I'd be glad to try to help.
Thanks,
VP