I have a chart that displays for both water and smoke, it fetch from my firebase project. why is it when I add data for my water to be display in the graph, it waits for the smoke data to be displayed first before showing the water data in the graph?
var database = firebase.database();
var ctx = document.getElementById('combinedChart').getContext('2d');
var combinedChart = new Chart(ctx, {
type: 'line',
data: {
labels: [],
datasets: [{
label: 'Smoke Sensor Value',
data: [],
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgba(255, 99, 132, 1)',
borderWidth: 1
},
{
label: 'Water Sensor Value',
data: [],
backgroundColor: 'rgba(54, 162, 235, 0.2)',
borderColor: 'rgba(54, 162, 235, 1)',
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
database.ref('smokeNumber').on('value', function(snapshot) {
var smokeData = snapshot.val();
var time = new Date().toLocaleTimeString();
combinedChart.data.labels.push(time);
combinedChart.data.datasets[0].data.push(smokeData);
if (combinedChart.data.labels.length > 10) {
combinedChart.data.labels.shift();
combinedChart.data.datasets[0].data.shift();
}
combinedChart.update();
});
database.ref('waterNumber').on('value', function(snapshot) {
var waterData = snapshot.val();
var time = new Date().toLocaleTimeString();
combinedChart.data.datasets[1].data.push(waterData);
if (combinedChart.data.labels.length > 10) {
combinedChart.data.datasets[1].data.shift();
}
combinedChart.update();
});
I want to display both my data in the chart simultaneously not waiting one of the data to display first before showing the other data.
The issue you're encountering stems from how you're handling the incoming data and updating the chart for smoke and water sensor values. Your current approach updates the chart's labels and the smoke dataset every time a new smoke value is received, but it only updates the water dataset (without adding a new label) when a new water value is received. This approach can lead to synchronization issues between your labels and datasets, as you've noticed.
To resolve this, you should ensure that both the smoke and water data updates include a new timestamp and manage the length of your labels and datasets consistently for both. Here's a refined approach:
This solution introduces a updateChartWithNewData function that handles updating the chart for both smoke and water data in a consistent manner. It ensures that a new timestamp is added only when necessary, and it maintains the labels and datasets sizes consistently, preventing the desynchronization issue you were experiencing.
Try this approach, and it should solve your problem efficiently.