Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does 'then(res => res.json())' in react-native fetch mean? [duplicate]

What is meant by then(res => res.json()) in the snippet below in react-native fetch?

fetch(url)
      .then(res => res.json())
      .then(res => {
        this.setState({
          data: res,
          error: res.error || null,
          loading: false
        });
like image 781
Aniket Singh Avatar asked Oct 05 '17 06:10

Aniket Singh


2 Answers

That's not really a react question since fetch and then are parts of js itself.

fetch returns an object as Promise that contains various information like headers, HTTP status etc. etc.

You have res.json() and various other possibilities. .json() will just return the body as promise with json content.

For more info: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

You can return the data as following:

  • .arrayBuffer()
  • .blob()
  • .json()
  • .text()
  • .formData()
like image 118
GottZ Avatar answered Oct 15 '22 02:10

GottZ


Your code part:

res => res.json()

is an ES6 arrow function, which is translated to:

function(res){
    return res.json();
}

And, about the json() function:

The json() method of the Body mixin takes a Response stream and reads it to completion. It returns a promise that resolves with the result of parsing the body text as JSON.

Read more here.

like image 33
Duc Filan Avatar answered Oct 15 '22 04:10

Duc Filan