0👍
✅
Try placing the chart.js code only when firebase has loaded and performed its needed actions.
Try this:
var myStates = [];
var myTimes = [];
// Variables to hold the count for each state
var TrumpCount = 0;
var BidenCount = 0;
// Define database connection to correct child branch, MyTemperature
var myDBConn = firebase.database().ref("USvote");
// Function that acts when a 'new child is added to the DB' - i.e. new data is added this function runs.
myDBConn.on("child_added", function(data, prevChildKey) {
TrumpCount = 0;
BidenCount = 0;
// The data returned from the branch is put into a variable, dataPoint
var dataPoint = data.val();
// Populate the lists with the various data from the database
myStates.push(dataPoint.USvote);
myTimes.push(dataPoint.Time);
// add 1 to the appropriate counter
for (i = 0; i < myStates.length; i++) {
if (myStates[i] == "Trump") {
TrumpCount = TrumpCount + 1;
}
if (myStates[i] == "Biden") {
BidenCount = BidenCount + 1;
}
}
// Update the page elements with the results of each count
document.getElementById("TrumpCount").innerHTML = TrumpCount;
document.getElementById("BidenCount").innerHTML = BidenCount;
// JS code for using charts
JSC.Chart("chartDiv", {
type: "column",
series: [
{
points: [{ x: "Biden", y: BidenCount}, { x: "Trump", y: TrumpCount}]
}
]
});
});
Source:stackexchange.com