Home > Blockchain >  Display results of an API request on HTML page using JavaScript
Display results of an API request on HTML page using JavaScript

Time:06-26

I have to build a page where the infos of countries (such as name, population, etc) are displayed using an API. I have managed to show the request results on the console using fetch, but I don't know how to display the results in the HTML page. I'm a beginner and very unexperienced. I know very little js.

I've seen other topics like this one, but they didn't really help solve my problem. One of them had an answer that suggested a code like the following, which worked fine until line 7 of the js script. However after adding the rest of the code I get an error that says Uncaught (in promise) TypeError: data is undefined. I don't understand why it says data is undefined when it has been used before.

function displayAll() {
  let countriesList = [];
  let url = "https://restcountries.com/v3.1/all";

  fetch(url).then(function(response){
    response.json().then(function(data) {
      console.log(data);  // works fine up until here
    })
    .then((data) => { // error says that 'data' is undefined
      let countries = document.getElementById("countries-container");
      data.results.forEach((item) => {
        countriesList.push(item.name);
        let div = document.createElement("div");
        div.innerText = item.name;
        countries.appendChild(div);
      })
      console.log(countriesList)
    })
  });
}
<body onl oad="displayAll()">

  <header>Countries</header>
  
  <div  id="countries-container">
  
    <!-- This is where the results will be displayed -->
  
  </div>

  <script src="./assets/scripts.js"></script>
  
</body>

I want to add new elements to serve as cards (one for each country).

Something tells me there will be more errors because the results printed in the console seem a bit too complicated to iterate, since it seems to be a matrix:

snipet of request result

snipet of request result expanded

I'm not using any frameworks, since I still need to learn more about the basics before jumping into the more fancy stuff. The code is just HTML, CSS and JavaScript and I want to keep it that way if possible. I've tried learning React alreaddy and I think I'm not ready yet... Anyway, if anybody can help me with this, I'll be very grateful.

CodePudding user response:

I've managed to solve the problem. Adding return data to the first .then solved the data undefined error, but then I got another error: TypeError: cannot read properties of undefined (reading forEach). This error disappeared after I deleted results from data.results.forEach

I could finally make the data appear in the HTML page, but it was shown as [object Object] and JSON.parse() would thow another error about an unexpected character somewhere in the original data. So I realized that I had to create the HTML elements to be able to show the data in the page. Obvious, I know. But as I said: I'm a total beginner.

So with that in mind, I created the following code and it works just fine! Turns out I didn't really need a list of all the countries, so I eliminated that from the code.

// Searches and shows the data of all the countries in the homepage upon loading

function displayAll() {
  let url = "https://restcountries.com/v3.1/all";

  fetch(url).then(function(response){
    response.json().then(function(data) {
      console.log(data);
      return data;
    })
    .then((data) => {      
      data.forEach((item) => {
        showCountryHome(item);
      })
    })
  });
}

// Creates a card for each country with the information I want

function showCountryHome(data) {
  let countries = document.getElementById("countries-wrapper");
  let div = document.createElement("div");
  div.className = "card";
  div.innerHTML = `<img src="${data.flags.svg}" width=200>
                   <p>${data.name.common}</p>
                   <p>Population: ${data.population}</p>
                   <p>Region: ${data.region}</p>
                   <p>Capital: ${data.capital}</p>`
  countries.appendChild(div);
}

  • Related