Tips for extracting information from Firebase and showing it on a Google gauge chart

I'm having some trouble displaying data from Firebase on a gauge chart. I keep getting an error that says "Uncaught (in promise)". Here's the JavaScript code I've been working with:

<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>

Answer №1

When pulling data from Firebase, it is important to remember that the process is asynchronous. This means that there might be a delay in fetching the data. While the data is being loaded, your main code will continue to run, leading to instances where certain functions get executed before the data is available.

In situations like this, such as when using chart.draw(data, options) before retrieving actual temperature data with

Temperature= snap.val().Temperature
, it can result in an empty chart since the necessary data hasn't been fetched yet.

To address this issue, it's crucial to ensure that any code relying on database data is placed inside the callback function or called from there directly. One possible solution involves restructuring your code as follows:

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);
    });
}

For further insights, you may refer to:

  • Understanding Why Firebase Loses Reference Outside the once() Function

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing data retrieval caching in nextjs getServerSideProps() for optimized performance

I am currently developing an application using nextjs that retrieves data from a firebase firestore. The issue I am facing is that the application makes these requests on every page load, even when the data does not need to be completely up to date. To add ...

When attempting to upload a picture using the camera, the file upload process is unsuccessful

Whenever I attempt to upload an image from my existing files, everything goes smoothly. However, if I try to select a file by directly clicking on the camera icon on my mobile device, it fails with a "CORS Error" message. I have tried adding and removing t ...

The hexagons configuration for tsParticles is experiencing technical difficulties

I'm struggling to implement the tsParticles library (specifically using react-tsparticles) in combination with the latest version of Next.js. However, when I try to use the particle.json file and bind it to the <Particles/> component, the partic ...

Arranging DIVs in a vertical layout

Currently, I am working on a design that involves organizing several <DIV> elements in a vertical manner while still maintaining responsiveness. Here are some examples: Wider layout Taller layout I have tried using floats, inline-block display, ...

Use React to increment a variable by a random value until it reaches a specific threshold

I am currently working on creating a simulated loading bar, similar to the one seen on YouTube videos. My goal is for it to last 1.5 seconds, which is the average time it takes for my page to load. However, I have encountered an issue with the following co ...

Ways to update a component upon becoming visible in Angular

Within my Angular 4.3.0 project, the header, left panel, and right panels are initially hidden on the login page until a successful login occurs. However, once they become visible, the data is not pre-loaded properly causing errors due to the ngOnInit meth ...

Acquiring variables from a JQuery Ajax request while invoking a JavaScript file

I'm currently experimenting with using JQuery Ajax to retrieve a javascript file. I need to pass some parameters to it, but I'm not entirely sure how to do so in Javascript (PHP seems easier for this). Here is my current setup: function getDocum ...

What is the best way to retrieve seat number upon clicking in React Native?

I have implemented a for loop and assigned its value in the click function to retrieve the seat number when a seat is clicked. However, I am only getting the last number of the for loop every time a seat is clicked. Can someone guide me on how to obtain th ...

Unlocking the potential of Three.js with mouse picking

I am looking to implement object picking in the following code snippet: var Three = new function () { this.scene = new THREE.Scene() this.camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 1000) this.camera.po ...

Utilizing jQuery to access Flash functions

When trying to access functions in my SWF using jQuery code, I encounter a compatibility issue with Internet Explorer. The code works fine in all other browsers except for IE. As jQuery is supposed to provide cross-browser functionality, writing addition ...

Challenges with Access-Control-Allow-Origin within the website's domain

Why am I encountering an issue when attempting to make an XMLHTTPRequest from a JavaScript file to a web service on the same domain, resulting in: Access-Control-Allow-Origin error stating that the origin is not allowed? Switching mydomain.com to localh ...

Utilizing async/await in JavaScript within a class structure

I am facing a dilemma in using the new async/await keywords within the connect method of my JavaScript class. module.exports = class { constructor(url) { if(_.isEmpty(url)) { throw `'url' must be set`; } ...

Guide on positioning a span element to the left using the margin auto property in CSS for Angular 4

Having trouble with moving numbers highlighted to the left with names in CSS. I've tried using flex direction and margin auto but can't achieve the desired result. https://i.sstatic.net/kRJOb.png Here is my HTML code: <section class="favorit ...

Encountering an unexpected token in the JSON file at the very start is causing an

An unexpected error has occurred, showing the following message:- Uncaught SyntaxError: Unexpected token u in JSON at position 0 The code causing the error is as follows:- import { useEffect, useState } from "react"; import { useNavigate, usePar ...

NG-show does not function properly with Angular validation messages when there are two input fields present

I have created a form with two modes: 'Create' and 'Edit'. Depending on the mode selected, specific div content is displayed in different areas of the layout. The content of the div includes an input field and validation messages relate ...

Exploring the capabilities of JavaScript on the iOS platform

Here is the code I've written for my iOS application: webView = [[UIWebView alloc] init]; webView.delegate = self; [webView loadHTMLString:@"<script type=\"text/javascript\" src=\"myFile.js\"></script& ...

Transform the characters within a string into corresponding numerical values, calculate the total sum, and finally display both the sum and the original string

I'm looking to convert a string containing a name into numerical values for each character, ultimately finding the sum of all characters' numerical values. Currently, only the first character's value is being summed using .charAt(). To achie ...

What is the best method for converting an Object with 4 properties to an Object with only 3 properties?

I have a pair of objects: The first one is a role object with the following properties: Role { roleId: string; name: string; description: string; isModerator: string; } role = { roleId:"8e8be141-130d-4e5c-82d2-0a642d4b73e1", ...

When displaying a collection of components, clicking a button will always select the most recent element in the array

Can you explain why this code won't work in a React environment? Every time the button is clicked, it picks up the value "name" from the last element in the array. In this example, the dialog will always display the name "John2". import React from "r ...

Unable to invoke parent method from child component in Vue causing issue

I am facing an issue where I am trying to trigger a method in the parent component from the child component using $emit, but for some reason, it is not working as expected. Can someone please help me troubleshoot this problem? Parent Component <templat ...