Reputation: 51
I am working with Chart.js. I have a chart that can display the data. I also have different datasets that I would like to interchange on a button press.
All the datasets are in an array and should just be interchanged with my method. Once I changed all the values, I call the update()
method. Nothing happens!
I have checked the content of char.data.datasets.data
and it does in fact contain the current data. The only thing is, that Chart.js does not seem to want to update.
What am I missing here?
The function that updates the chart:
let getValues = function(dataset, label)
{
return firebase.database().ref("/data/" + dataset).once("value").then(function(snapshot)
{
var amazon = snapshot.val().Amazon;
var google = snapshot.val().Google;
var facebook = snapshot.val().Facebook;
var twitter = snapshot.val().Twitter;
chart.data.datasets.data = [];
chart.data.labels = [];
chart.data.datasets.label = null;
chart.data.datasets.data = [amazon, google, facebook, twitter];
chart.data.labels = names;
chart.data.datasets.label = label;
chart.update();
console.log(chart.data.datasets.data);
});
}
If you need any more information please let me know.
Upvotes: 5
Views: 15303
Reputation: 8746
chart.data.datasets
is an array of datasets, not a single dataset. datasets
does not have its own data
and label
attributes. Rather, each individual dataset
in the array has its own data
and label
attributes. You therefore cannot do datasets.data
or dataset.label
.
If you want to update the data
or label
variable of a specific dataset, you need to select that object from the array. To select the first dataset, simply use datasets[0]
:
chart.data.datasets[0].data = [amazon, google, facebook, twitter];
chart.data.datasets[0].label = label;
If you want to update all datasets, use a forEach
loop to iterate through the array:
chart.data.datasets.forEach((dataset) => {
dataset.data = [amazon, google, facebook, twitter];
dataset.label = label;
});
Two more points:
One other possible problem is that the names
variable is not initialized anywhere, though it could be that you just didn't include that part of the code in your question.
Also, why do you have the following three lines of code, if you just reassign all the values in the next three lines of code?
chart.data.datasets.data = [];
chart.data.labels = [];
chart.data.datasets.label = null;
Upvotes: 9