javascripthtmlfetch-api

Cannot send property of fetched data to innerHTML


I am somewhat new to JavaScript and wanted to fetch sensor data from a remote site and display it on a local page in a DIV element. There are two properties of the fetched data: name and value.

When it gets to the line in the script: document.getElementById('sensorValue').innerHTML = data.value; the console displays a error message "Cannot read properties of undefined (reading 'value')".

A few lines above, the script successfully fetches and sends data.value to the console.log.

I cannot figure out how to get the data.value into the DIV element using innerHTML.


    <html>
    <body>
    <h2>fetch & innerHTML test</h2>

    <div id='sensorValue'></div>

    <script>

        fetch("https://example.com/filename.php?apikey=1567477555629&setting1=1" )
        .then( response => {

        if( ! response.ok ) {
            throw new Error("Could not fetch resource")
        }
        return response.json()
        })

        .then( data => console.log(data.value))   

        .then(data => {
        document.getElementById('sensorValue').innerHTML = data.value;
        })
        .catch( error => console.error(error));

    </script>
    </body>
    </html>

I changed the line in question to assign a string instead of data.value: document.getElementById('sensorValue').innerHTML = "Test"; and it filled the DIV with id='sensorValue' successfully.

Thank you for your insight!


Solution

  • This callback returns undefined:

    .then(data => console.log(data.value))
    

    So in the next callback data will be undefined:

    .then(data => {
      document.getElementById('sensorValue').innerHTML = data.value;
    })
    

    Either remove that first one, or combine the two operations:

    .then(data => {
      console.log(data);
      document.getElementById('sensorValue').innerHTML = data.value;
    })
    

    Or, if you want to keep them separate, return the value:

    .then(data => {
      console.log(data.value);
      return data;
    })