Search code examples
javascriptfetch

Error on loading data into variable from fetch


I'm trying to build a webpage using JS/HTML/CSS only (no frameworks), but when trying to assign the response into a variable, seems like the flow isn't in the order I've wrote:

var COUNTRIES_DATA = "";

function fetchCountriesData(){
fetch(`${API_URL}/countries`).then(response => {
  return response.json().then(countries => {
    COUNTRIES_DATA = countries;
  });
});
};

fetchCountriesData();
renderCountriesCombo(COUNTRIES_DATA);


function renderCountriesCombo(countries) {
  countries.sort(function (a, b) {
    return (a.Country > b.Country) ? 1 : ((b.Country > a.Country) ? -1 : 0);
  });
  let options = countries.map(country => {
    return `<option>${country.Country}</option>`
  })
  document.getElementById("combo").innerHTML = options;
}

The error message I'm getting is countries.sort is not a function, but when I debug the value of countries inside the renderCountriesData() the countries variable is empty.

Break points on ->

  • fetch('${API_URL}/countries').then
  • fetchCountriesData();
  • countries.sort(function (a, b) {

The flow when I'm debbuging looks like:

starts on fetchCountriesData() -> since I've a <body onload="fetchCountriesData()"> goes the the function signature (1st line), doesn't run the return method, next it goes to the renderCountriesCombo() function and give the error message, then goes back to the fetchCountriesData() and populate the COUNTRIES_DATA.

The problem is, that I need that COUNTRIES_DATA variable to be populated before any other method runs.


Solution

  • fetch() is network promise, after call promise the renderCountriesCombo is execute immediate, meanwhile the data is fetching, not completed.

    you should do like this:

    fetchCountriesData().then(countries => renderCountriesCombo(countries))