Search code examples
javascripthtmljsonfetch

JSON, fetch, javascript in HTML and undefined or empty string


I was searching a forum for issues related to JSON and fetch function. There is bunch of them but i have hard time to understand this. What do i need is to fetch "/api" url that returns:

{"lux": 0, "pressure": 0.0, "TVOC": 0, "temp": 0.0, "hum": 0.0, "AQI": 0, "eCO2": 0}

I want to populate fields in a HTML table with these values. I started with simple thing in my HTML code:

<script>
async function get_data() {
  await fetch('/api')
    .then(resolve => resolve.json())
    .then(data => jdata = data);
  return jdata;
}

const JD = () => {
  fetch('/api')
    .then(resolve => resolve.json())
    .then(data => jdata = data);
}

//let raw_data='{"lux":0, "pressure":0, "TVOC":0, "temp":0, "hum":0, "AQI":0, "eCO2":0}';
//jdata=JSON.parse(raw_data);
let raw_data = get_data();
jdata = JSON.parse(raw_data);

console.log(raw_data);
console.log(jdata);
console.log(JD);
console.log(jdata.lux);

document.getElementById("dane_temp").innerHTML = jdata.temp;</script>

When i do this then I get error

Uncaught SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data line

so i comment JSON.parse line out. The issue is that raw_data is a promise object and i can't get that JSON data right to assign to jdata variable. I'm generally having issue to get out these nested objects to something that i can parse. When i assign string, as in commented out section, then I can do JSON.parse and all works, but then raw_data is not an object it is simply the string. But with this async function this is what sits in the raw_data:

Promise { <state>: "pending" }
​
<state>: "fulfilled"
​
<value>: Object { lux: 0, pressure: 0, TVOC: 0, … }
​
<prototype>: Promise.prototype { … }

JD gets a function object and i don't see any data in it. I went through different posts on this forum and due to fact that i typically do not program in JS i'm having issues to understand how to pull out a string from that promise object. Can you help me with this?


Solution

  • Try this

    <script>
    async function get_data() {
        try {
            const response = await fetch('/api');
            const jdata = await response.json();
            return jdata;
        } catch (error) {
            console.error("Error fetching data:", error);
            return null; // Return null if an error occurs
        }
    }
    
    // Example of handling the data
    async function updateData() {
        const jdata = await get_data(); // Wait for the data to be fetched
        if (jdata) { // Check if the data is successfully fetched
            console.log("Received data:", jdata);
            console.log("Lux value:", jdata.lux);
    
            // Update DOM elements with received data
            document.getElementById("dane_temp").innerHTML = jdata.temp;
        } else {
            console.error("Failed to fetch or parse data");
        }
    }
    
    // Call the updateData function after the DOM is ready
    document.addEventListener("DOMContentLoaded", () => {
        updateData();
    });
    </script>