Can't use data returned from Fetch API

Viewed 749

I am trying to get data from this API using fetch, and I know a promise pending is returned, but it isn't resolving itself so I can't use the data. I don't know what I am doing wrong.

function api () {
    return fetch('https://api.punkapi.com/v2/beers').then(respo => { respo.json() } ).then(data => { 
        const beersData = data;
        return beersData;
    }).catch(error => {
        console.error(error)
     }) ; 
}

api();

console.log(beersData)

1 Answers

First of all, you need to remove curly bracket in first then. respo => respo.json() is equivalent to respo => { return respo.json() }.

And second, you need to handle promise when you call api function since api() also returns Promise.

function api () {
  return fetch('https://api.punkapi.com/v2/beers')
    .then(respo => respo.json())
    .then(data => { 
      const beersData = data;
      return beersData;
    }).catch(error => {
      console.error(error)
    }) ; 
}

api()
.then(res => {
  console.log(res);
})

Related