Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native fetch() returns odd json response items

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

like image 581
Ilyas Khametov Avatar asked Mar 07 '23 21:03

Ilyas Khametov


1 Answers

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.

UPDATE

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 */);
like image 122
Ilyas Khametov Avatar answered Mar 10 '23 13:03

Ilyas Khametov