Mayur Patil
Mayur Patil

Reputation: 130

Why there are 2 then blocks in fetch call in React?

I am using fetch api to bring data from back-end and it is working as expected for me. However I am not able to figure out why there is a need of 2 then blocks in fetch call.

Upvotes: 3

Views: 5302

Answers (3)

mostafa tourad
mostafa tourad

Reputation: 4388

Fetch API uses promises and it takes a request as a parameter and return a promise that resolve to a Response Object that response object has information about the server response like status code and headers and the body of the response which is the data you want , and some of the methods on that Response Object return Promise too so you need to make another then block , methods like response.json() response.text() response.blob() , so this is why you need two then blocks , the first resolve the response from the server and the second get the data from the response . learn more

Fetch API

javascript Promise

Using Fetch API

Upvotes: 11

Khabir
Khabir

Reputation: 5862

Fetch returns Promise (Easy article of Promise) and you need to resolve promise to access data. To resolve a promise, you need to use then()

A basic fetch example:

fetch('https://jsonplaceholder.typicode.com/todos')
  .then(response => response.json())
  .then(data => console.log(data, 'Data'));

In the above example, fetch returns promise, so it is resolved in first then() where it is getting response object that is representation of the entire HTTP response. So to extract the JSON body content from the Response object, we need to use the json() method, which returns a second promise that resolves with the result of parsing the response body text as JSON. Click here for More Detail

Here I run a fetch using online js compiler and show the output in console. Please have a look at description in the picture.

enter image description here

Upvotes: 4

GhostfromTexas
GhostfromTexas

Reputation: 169

Without seeing your code, I assume the promise being returned and reconciled in the first "then" block has another asynchronous call with it's own return. For instance...

foo() //returns a promise
.then(() => { // called when "foo" resolves the promise
    return bar();
})
.then(() => { // called when "bar" resolves the promise
})
.catch((err) => { //errors
});

If the first "then" block isn't returning another promise, I don't think the 2nd block will be called.

Upvotes: -1

Related Questions