1

I tried to get data from firebase to display on gauge chart but it's doesn't show anything and shown error "Uncaught (in promise)

Here's my js code.

<script type="text/JavaScript">
  google.charts.load('current', {'packages':['gauge']});
  google.charts.setOnLoadCallback(drawChart);

  function drawChart() {
      var database = firebase.database();
         var Temperature;
            database.ref().on("value", function(snap){
                
                Temperature= snap.val().Temperature;
                
        });

    var data = google.visualization.arrayToDataTable([
      ['Label', 'Value'],
      ['Memory', Temperature]
    ]);

    var options = {
      width: 400, height: 120,
      redFrom: 90, redTo: 100,
      yellowFrom:75, yellowTo: 90,
      minorTicks: 5
    };

    var chart = new google.visualization.Gauge(document.getElementById('chart_div'));

    chart.draw(data, options);

    
  }
</script>
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

1 Answers1

1

Data is loaded from Firebase asynchronously, since it may take some time. While this is happening, your main code will continue to run. Then once the data is available, your callback is called.

This means that right now, your chart.draw(data, options) runs before the Temperature= snap.val().Temperature has been executed. That explains why you don't see any data in your chart.

The solution is always the same: any code that needs the data from the database, needs to be inside the callback, or be called from there. So in your case, the simplest fix is:

  function drawChart() {
      var database = firebase.database();
      var Temperature;


      var options = {
        width: 400, height: 120,
        redFrom: 90, redTo: 100,
        yellowFrom:75, yellowTo: 90,
        minorTicks: 5
      };

      var chart = new google.visualization.Gauge(document.getElementById('chart_div'));

      database.ref().on("value", function(snap){
          Temperature= snap.val().Temperature;
                
          var data = google.visualization.arrayToDataTable([
            ['Label', 'Value'],
            ['Memory', Temperature]
          ]);
          chart.draw(data, options);
      });
  }

Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807