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 onload="displayAll()">
<header>Countries</header>
<div class="container" 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:
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.