crayden
crayden

Reputation: 2280

What is "result" when using the Fetch API?

I have seen a few examples online that use result within a then method chained onto the fetch method. In an effort to try to understand result in the Fetch API, the following code was created. The JSON returns fine and is logged to the console. result is undefined. What exactly is result, and why is it undefined?

fetch('https://cat-fact.herokuapp.com/facts', {
  method: 'get'
})
.then((response) => {
  console.log(response)
})
.then((result) => {
  console.log(result)
});

Upvotes: 0

Views: 1106

Answers (3)

Bhautik Chudasama
Bhautik Chudasama

Reputation: 712

The simplest use of fetch() takes one argument — the path to the resource you want to fetch — and returns a promise containing the response (a Response object).

You can checkout Response object interface https://developer.mozilla.org/en-US/docs/Web/API/Response

Response object has a method json() which is used to parsing the body text as JSON.

fetch('https://cat-fact.herokuapp.com/facts', {
  method: 'get'
})
.then((response) => {
  console.log(response) // Response object
  return response.json() // Return a promise
})
.then((result) => {
  console.log(result) // We get out body text as JSON
});

You can use async/await

async function fetchCats() {
      let response = await fetch("https://cat-fact.herokuapp.com/facts");
      let result = await response.json();
      console.log(result);
}

fetchCats();

Upvotes: 0

brk
brk

Reputation: 50326

You need to return response from first then & extract JSON payload from that response once the request completes. Similarly if you wish to use the result of this fetch call you have to return the response from the second then or add code for consuming the response

fetch('https://cat-fact.herokuapp.com/facts', {
    method: 'get',
    headers: {
      'Content-Type': 'application/json',
    },
  })
  .then((response) => {
    return response.json();
  })
  .then((result) => {
    console.log(result)
  });

Upvotes: 4

CertainPerformance
CertainPerformance

Reputation: 371049

When in a .then chain, the argument of a .then will be the resolve value of the value returned from the previous .then in the chain. Here, since you aren't returning anything from the first .then, the second .then's argument is undefined.

You probably meant to do something like

.then((response) => {
  console.log(response)
  return response.json();
})

Upvotes: 1

Related Questions