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

Viewed 25083

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
        });
3 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()

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.

Javascript fetch function asynchronously pulls a resource from the specified url. Meanwhile fetch returns a Promise. Promise helps with the asynchronous part and runs the function passed into then (res => res.json()) once the resource is loaded with the fetched resource as parameter. The fetched resource can be parsed using json() if it is JSON formatted.

then also returns a Promise making it chainable.

fetch(url) // asynchronously load contents of the url
           // return a Promise that resolves when res is loaded
      .then(res => res.json()) // call this function when res is loaded
      // return a Promise with result of above function
      .then(res => { // call this function when the above chained Promise resolves
        this.setState({
          data: res,
          error: res.error || null,
          loading: false
        });

res => res.json() can also be written as (but not exactly equal)

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