Search code examples
javascriptfetch

Javascript fetch api


i'm trying to assign the variable countries to the response of the fetch api but when i print out countries i get undefined ? can anyone explain to me why ? and a solution if it is possible.

async function getCountries(url) {
    const data = await fetch(url);
    const response = await data.json();
    return response;
}

let countries;

document.addEventListener('DOMContentLoaded', () => {
    getCountries('https://restcountries.eu/rest/v2/all')
    .then(res => countries = res)
    .catch(err => console.log(err));

})

console.log(countries);

Solution

  • function getCountries(url) {
        return new Promise((resolve,reject)=>{
            fetch(url).then(res => {
                //You can parse the countries from the api response here and return to the 
                //event listener function from here using the resolve methood call parameter
                resolve(res);
            })
            .catch(err => console.log(err));
        })
    }
    
    document.addEventListener('DOMContentLoaded', () => {
        getCountries('https://restcountries.eu/rest/v2/all')
        .then(res => {
            //the returned value after api call and parsing will be available here in res
        })
    })
    

    Or if you dont want another function for this one you can directly get it using the following way,

    document.addEventListener('DOMContentLoaded', () => {
        let countries;
        fetch('https://restcountries.eu/rest/v2/all')
        .then(res => {
            //the returned value after api call and parsing out the countries hereit self
            countries = res.data.countries;
        })
    })