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
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 */);
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