Search code examples
javascriptarraysxmlhttprequest

Pushing data from an API to an Array


I'm having trouble understanding how to pass along data from an API to an array. What I'm trying to do is to fetch the current population of a country and then put it in the array. Which country depends on the input.

Am I on the right track? How can I do this? I've tried so much different, and this code is the latest I've gotten.

document
  .querySelector("#newListElement")
  .addEventListener("submit", function(e) {
    e.preventDefault();

    getCountry(country).then(function() {
      list.push({
        id: uuidv4(),
        text: e.target.elements.text.value
        /* How do I send along Country Population Today with this object?*/
      });

      saveListElements(list);
      renderList(list);
      e.target.elements.text.value = "";
    });
  });

function getCountry(country) {
  var url = `http://api.population.io/1.0/population/${country}/today-and-tomorrow`;

  return new Promise(function(resolve, reject) {
    var request = new XMLHttpRequest();
    request.open("GET", url, true);
    request.responseType = "json";

    request.onload = function() {
      if (request.status === 200) {
        resolve(request.response);
      } else {
        reject(Error(request.statusText));
      }

      request.onerror = function() {
        reject(Error("Network Error"));
      };

      request.send();
    };
  });
}

Solution

  • I suggest you read that page before going further

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises

    //the promise's result is the first argument of the resolve handler.
    getCountry(country).then(function(myResult) { 
          list.push({
            id: uuidv4(),
            text: e.target.elements.text.value,
            result:myResult
          });
    
          saveListElements(list);
          renderList(list);
          e.target.elements.text.value = "";
        });