0

I'm trying to get the items of an external API and although the results are showing in the console, I'm having some trouble trying to pull the data and interpret it into a HTML output.

I create a const called makeRequest for example which pulls data from the API when I try to convert it to a string or use innerHTML to pull into a class, I get either "object promise" or undefined.

I'm stumped. Any ideas? I'm sure I'm missing something obvious but I haven't been practising JS for long.

EDIT: I'm able to return the data to the console log but I'm unable to get that response to become a string and parse into HTML

https://codepen.io/iambeeroy/pen/dKJjQw

    //Request is defined and
const request = options => {
  return fetch(options)
    .then((response) => {
        return response.json();
    })       
    .then((data) => {
        return data;
    })
    .catch(error => console.error(error));
};

//Logs the request in the console
const makeRequest = request('https://api.punkapi.com/v2/beers?abv_gt=6');
console.log(makeRequest);

var res = makeRequest.toString();
document.getElementById("beers").innerHTML = res;
iambeeroy
  • 13
  • 3

1 Answers1

0

This isn't how promises work. The bits inside the then() and catch() callbacks execute after the rest of the code. So your makeRequest variable will be a Promise object, and you can't convert it into a string. It's not actually data, it's a promise to deliver data at some point in the future.

Anything that you want to do with the promised data has to be done inside callbacks, like this:

    //Request is defined and
const request = options => {
  return fetch(options)
    .then((response) => {
        //this gets passed on to other .then() calls
        return response.json();
    })
    .catch(error => console.error(error));
};


const makeRequest = request('https://api.punkapi.com/v2/beers?abv_gt=6')
   .then(data => {
       //this will get the response.json() result from the fetch callback above
       var res = data.toString();
       document.getElementById("beers").innerHTML = res;
   });
Duncan Thacker
  • 5,073
  • 1
  • 10
  • 20