Context not found using Chart.js

Viewed 84

I am getting data from firebase database and on each retrieval of item Im adding HTML code to make a modal and canvas in the modal. Im not getting any error but my canvas is not showing up. I'm using chart.js. Can someone please help?

sensors.on("child_added", function(snapshot) {
  var sensor = snapshot.val();

  document.getElementById('bod').innerHTML += '<div class="modal fade" id="'+sensor.name+'Modal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"><div class="modal-dialog" role="document"><div class="modal-content"><div class="modal-header"><h5 class="modal-title" id="exampleModalLabel">'+sensor.name+'</h5><button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button></div><div class="modal-body">**<canvas id="'+sensor.name+'" style="width:100%;max-width:600px"></canvas>**</div><div class="modal-footer"><button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button><button type="button" class="btn btn-primary">Save changes</button></div></div></div></div>'
  document.getElementById("row").innerHTML += '<div class="col-sm-4 p-2"><div class="card"><img class="card-img-top" src="'+sensor.img+'" alt="Card image cap"><div class="card-body"><h5 class="card-title">'+sensor.name+'</h5><p class="card-text">View the data of your sensor.</p><a href="#" class="btn btn-primary btn-block" data-toggle="modal" data-target="#'+sensor.name+'Modal">View</a></div></div></div>'
});

var xValues = ["Mon","Tue","Wed","Thu","Fri","Sat","Sun","Mon","Tue","Wed","Thu"];
var yValues = [56,90,87,65,43,21,65,87,56,90,56];

new Chart(sensor.name, {
  type: "line",
  data: {
    labels: xValues,
    datasets: [{
      fill: false,  
      lineTension: 0,
      backgroundColor: "rgba(0,0,255,1.0)",
      borderColor: "rgba(0,0,255,0.1)",
      data: yValues
    }]
  },
  options: {
    legend: {display: false},
    scales: {
      yAxes: [{ticks: {min: 15, max:100}}],
    }
  }
});
1 Answers

I found the solution, I am using the firebase on function

sensor.on('value', ...)

which is always running because it is looking for on changes from the Firebase database.

I changed it to

sensor.once('value', ...)

This way I get all the data once and then work from there. I used a for loop after I get all this information and create 5 canvas elements.

Related