🚢

Javascript dynamic fetch

CatégorieCours

Cours de Julie Chaumard

To Do
ChaptersHomeworksExercisesWeeksDates
Javascript316/06/2025
17/06/2025

Create a quiz using country information retrieved from a web API.

Get the countries information from https://restcountries.com/v3.1/all?fields=name,flags,capital,region

⚠️

LOOPs

  • for (let i=0; i < data_nb; i++ ) {} object and Array
  • Use for...in to iterate over an object
  • Use for...of to iterate over an object
  • Use forEach() to iterate over an array

Create the project

This is the project architecture to create

[projectname]
		|____countries.php
		|____assets
							|____js
										|____countries.js
							|____css
										|____header.css
										|____footer.css
										|____main.css
							|____images
							|____fonts
		|____template-parts
							|____head.php
							|____header.php
							|____footer.php

Steps

  1. Link your JavaScript file to the web page (php file). To do this, add a script link just before the end HTML element </body>
    countries.php
    
    <script src="assets/js/countries.js"></script>
  1. Try to fetch the data from the REST COUNTRIES API. Display the data received in the console to check if the fetch command is working.
    In case of error, use a catch to :
    1. display the error message on the webpage to alert the visitor,
    1. send a mail to the webmaster.
    FETCH
    
    countries.js
    
    async function fetchCountries() {
      try {
        const response = await fetch("https://restcountries.com/v3.1/all?fields=name,flags,capital,region");
        const data = await response.json();
        console.log(data);
      } catch (error) {
        console.error("Erreur :", error);
      }
    }
  1. Store the information you retrieve in a JavaScript object to keep it temporarily in the program’s memory during the session.
    1. store in an object,
    1. display the content of the object in the console to verify that the code is working correctly.
    Structure of the object
    countries is the object
    "France" is the key of the occurence (line/row)
    const countries = {
      "France": {
        capital: "Paris",
        region: "Europe",
        flag: {
          png: "https://flagcdn.com/w320/fr.png",
          alt: "The flag of France is composed of three vertical bands..."
        }
      },
      "Brazil": {
        capital: "Brasília",
        region: "Americas",
        flag: {
          png: "https://flagcdn.com/w320/br.png",
          alt: "The flag of Brazil has a green field with a yellow diamond..."
        }
      },
      // etc.
    };
    countries.js
    
    // Object declaration with curly braces
    let countries = {};
    
    async function fetchCountries() {
        try {
            console.log("You are in the countries.js, function fetchCountries()")
            const response = await fetch("https://restcountries.com/v3.1/all?fields=name,flags,capital,region");
            const data = await response.json();
            console.log("THE DATA RECEIVED FROM THE FETCH :");
            console.log(data);
    
            let data_nb = data.length;
            //console.log("data_nb = ", data_nb);
    
            let country_name;
            
            for (let i=0; i < data_nb; i++ ) {
                country_name = data[i].name.common;
                countries[country_name] = {
                    capital: data[i].capital[0],
                    region: data[i].region,
                    flag: {
                        png: data[i].flags.png,
                        alt: data[i].flags.alt,
                    }
                };
            };
    
            console.log("MY COUNTRIES OBJECT :");
            console.log(countries);
    
        } catch (error) {
            console.error("The fetch is not working. ", error);
        }
    }
  1. List of country names and its capital in alphabetical order
    1. Display them inside a <div> element, using a list (<ul> or <ol>) to structure the output.
    countries.js
    
    // Number of countries in the object
    let countries_nb = Object.keys(countries).length;
    console.log("countries_nb = ", countries_nb);
    
    // List of country names in alphabetical order
    // 1. convert in an array : Object.keys(countries) create an array with the keys of the object
    // 2. Sort with the sort() method
    const countryNames = Object.keys(countries).sort();
    console.log(countryNames);
    
    // forEach on the array
    // find the information of the country in the object countries
    let country_html = "";
    countryNames.forEach(country => {
        console.log(`Country ${country} - Capital ${countries[country].capital}`);
        country_html += `<li>Country ${country} - Capital ${countries[country].capital}</li>`;
    });
    document.getElementById("countries_1").innerHTML = country_html;
    
    countries.js
    
    async function displayCountries() {
        await fetchCountries();
        prepareCountries();
    }
    countries.php
    
    <article>
        <h1>1. Fetch the Rest Countries to get the data</h1>
        <button onclick="displayCountries()">Fetch</button>
    
        <div>
            <ul id="countries_1">
            </ul>
        </div>
    
    
    </article>
  1. Display the countries : when you meet "Belarus" you continue the loop, when you meet "Croatia" you stop(break) the loop.
    1. Display them inside a <div> element, using a list (<ul> or <ol>) to structure the output.
    💡

    Difference between == and ===

    == to compare value

    === to compare value and type

        countries.js
        
        // Display the countries when you meet "Belarus" you continue the loop, when you meet "Croatia" you stop(break) the loop.
        // Loop for...in because countries is an object
        // country is the key
        country_html = "";
        for (let country in countries) {
            if (country === "Croatia") {
    			      break;
            }
            // Belarus will not be include in the output
            if (country == "Mayotte") {
    			      continue;
            }
            country_html += `<li>Country ${country} - Capital ${countries[country].capital}</li>`;
            
        }
        document.getElementById("countries_2").innerHTML = country_html;
    countries.php
    
    <div>
        <ol id="countries_2">
        </ol>
    </div>
  1. List the countries and filter them by region, or first letter, on the web page.
    1. Select some countries using a condition (for example, by region or by first letter — if country.name[0].toUpperCase() === "A").
    1. Display them inside a <div> element, using a list (<ul> or <ol>) to structure the output.
    1. Do the same output addin alphabetic order
    countries.php
    
    <div>
        <ul id="countries_3">
        </ul>
    </div>
    
    <div>
        <ul id="countries_4">
        </ul>
    </div>
    countries.js
    
    //List the countries for region : region : "Europe"
    country_html = "";
    for (let country in countries) {
        if (countries[country].region == "Europe") {
            country_html += `<li>Region ${countries[country].region} - Country ${country} - Capital ${countries[country].capital}</li>`;
        }
    }
    document.getElementById("countries_3").innerHTML = country_html;

    The same with alphabetic order

    countries.js
    
    // List of country names in alphabetical order
    // 1. convert in an array : Object.keys(countries) create an array with the content of the object
    // 2. Sort with the sort() method
    const countryNames = Object.keys(countries).sort();
        
    //List the countries for region : region : "Europe" in alphabetical order
    country_html = "";
    countryNames.forEach(country => {
        if (countries[country].region == "Europe") {
            country_html += `<li>Region ${countries[country].region} - Country ${country} - Capital ${countries[country].capital}</li>`;
        }
    });
    document.getElementById("countries_4").innerHTML = country_html;
💚

Agence digitale Parisweb.art
Tout savoir sur Julie, notre directrice de projets digitaux :
https://www.linkedin.com/in/juliechaumard/