Reputation: 298
I'm trying to get data as JSON from service called OpenWeatherMap, so in my componentWillMount method I'm calling fetch() to return data by url. My code for now is:
this.weather = fetch(url).then(response => response.json()).then(responseJson => responseJson);
It works, but returns odd data within JSON response, my JSON response for now is:
{"_40":0,"_65":1,"_55":{here_the_correct_response}}
But I want my response to be without these strange underscore indexes, just pure JSON response
Upvotes: 4
Views: 2669
Reputation: 298
Ok, I figured it out by myself. This odd data is so called promise returned by fetch()
. In order to get rid of this I did so:
fetch(url)
.then(response => response.json().then(data => data))
.then(result => /* Do whatever you want with this result */)
.catch(error => /* Do something if error occurs */);
I don't know why I should do "promise decryption" twice, but it works. Any comments explaining this are appreciated.
Thanks to vdj4y's answer I now understand it correctly.
fetch()
function is not returning a promise, as I wrote previously. It returns a Response
object that contain information about request/response (like its statuses) and the data we need in ReadableStream
format.
json()
function, in turn, returns a promise that contain result of converting ReadableStream
to plain js object. In order to manipulate data returned by promise, then()
function is needed.
Corrected code here:
fetch(url)
.then(response => response.json())
.then(result => /* Do whatever you want with this result */)
.catch(error => /* Do something if error occurs */);
Upvotes: 7
Reputation: 2669
Fetch return a Response object contain some information like the request/response status. and the data that you are interested with, which was returned by server is on Response.body.
This data is ReadableStream format. The response object has function which is json(), this will return a promise that contain result of converting readablestream to js object.
If your server send invalid json. the error will occur when you run response.json(), but not before.
fetch(url)
.then(response => {
console.log(response) // this contains some useful information about the reponse
return response.json(); // convert readable stream to js object, if json is invalid, you will get the error here
})
.then(result => /* Do whatever you want with this result */)
.catch(error => /* Do something if error occurs */);
Upvotes: 1
Reputation:
That behavior is correct, because response.json()
is actually a promise.
Use console.warn(new Promise.resolve())
to approve that. You will see a similar result.
Upvotes: 0