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
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With