Search code examples
javascriptjsonapifetch-apisimple-html-dom

Fetch Api data is displaying undefined in html webpage but working in console


function getdata() {
  fetch(
    "https://api.lrs.org/random-date-generator?year=2015&source=api-docs"
  )
    .then((response) => response.json())
    .then((data) => data)
    .then(function (data) {
      let htmldata = "";
      htmldata = `<tr>
            <th>Quarter</th>
            <th>Day</th>
            <th>Month</th>
            <th>Date of Birth-</th>
            <th>Longest Day</th>
            <th>Unix</th>
            </tr>`;
           

let ndata = JSON.stringify(data);
      for (r in ndata) {
        
        htmldata += `<tr>
            <td>${r.quarter}-</td>
            <td>${r.day}-</td>
            <td>${r.month}-</td>
            <td>${r.db}-</td>
            <td>${r.long}-</td>
            <td>${r.unix}</td>
            </tr>`;
      
      }
      
      document.getElementById("rdata").innerHTML = htmldata;
    });
}

getdata();

data is displaying in the console but not stored in htmldata variable nor displaying in a webpage(showing undefined). Api data is showing in Objects in console not working in any html page. and data is looping but values doesn't get stored, maybe?


Solution

  • The API returns an object with two properties, messages and data. You only need the data property.

    After that, loop through the values of the data property with Object.values(), which turns the object into an iterable object that exposes the values of the properties that you can loop over.

    function getdata() {
      fetch("https://api.lrs.org/random-date-generator?year=2015&source=api-docs")
      .then((response) => response.json())
      .then(({ data }) => data) // Return the data property
      .then(function (data) {
        let htmldata = `<tr>
          <th>Quarter</th>
          <th>Day</th>
          <th>Month</th>
          <th>Date of Birth-</th>
          <th>Longest Day</th>
          <th>Unix</th>
          </tr>
        `;
    
        for (const entry of Object.values(data)) {
          htmldata += `<tr>
            <td>${entry.quarter}-</td>
            <td>${entry.day}-</td>
            <td>${entry.month}-</td>
            <td>${entry.db}-</td>
            <td>${entry.long}-</td>
            <td>${entry.unix}</td>
            </tr>
          `;
        }
          
        document.getElementById("rdata").innerHTML = htmldata;
      });
    }
    
    getdata();