-1

I am currently learning how to work with APIs, and I am having a little trouble with fetching the data from an API. The code below successfully gets a response but does not actually get any data from the server. How do I go about solving this?

const onClick = () => {
fetch(
  `https://collectionapi.metmuseum.org/public/collection/v1/objects/45734`
)
  .then(res => {
    if (res.ok) {
      console.log(res)
      console.log('SUCESSS')
    } else {
      console.log("Not Successful")
    }
  })
  .then(data => {
    if (data) {
      console.log(data)
    } else {
      console.log("undefined data")
    }
  })
  .catch(error => console.log('ERROR'))

console.log(results);

}

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122

1 Answers1

0

The promise .then methods can be chained in a way each chained then methods will receive the returned value of the previous one. In your case, the first one does not return any values, making the second one receiving nothing, also well known as undefined.

As the url your code is calling return json content, you should return after loging success the result of res.json().

This will read the stream of the response body and parse it as json, using a promise.