Why does fetch return a strange hash of integers?

I am using the fetch API with React Native.

My answer follows the normal format {"message": "error here"} if status => 400, which I will show in my own popup.

I try to call response.json() after a failure is detected, but it keeps everything in a weird format ...

{ _45: 0, _81: 0, _65: null, _54: null }

For some reason ... the actual answer I want is in _65 ... I don't know what these random keys are.

Therefore, currently I need to access it through _bodyText , but I assume this is wrong, because it is a private underscore method.

What am I doing wrong?

 var API = (function() { var base = 'https://example.com/api/v1'; var defaults = { credentials: 'same-origin', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' } }; var alertFailure = function(response) { if (response.status >= 200 && response.status < 400) { return response; } else { var json = JSON.parse(response._bodyText || '{}'); var message = json.message || 'There was a problem. Close the app, and try again later.'; var error = new Error(message); error.response = response; throw error; } }; var callAPI = function(url, opts) { opts.headers['X-Version'] = 'v' + Package.version; return fetch(base + url, opts) .then(alertFailure) .then((response) => { return response.json(); }) .catch((error) => { Alert.alert(null, error.message); }); }; return { get: function(url, opts) { var fullOpts = Object.assign({}, defaults, opts); return callAPI(url, fullOpts); }, post: function(url, data, opts) { var fullOpts = Object.assign({}, defaults, { method: 'POST', body: JSON.stringify(data || {}) }, opts); return callAPI(url, fullOpts); } }; })(); 
+5
source share
3 answers

The answer is that .json() returns a promise ... so I had to do everything from .then()

+8
source

AsyncStorage.getItems always returns a promise. You can use this method below

  AsyncStorage.getItem("access_key").then((value)=> { console.log(value); }); 
+1
source

I would recommend that you use the new ES7 async/await syntax, they are easier to understand than using .then()

To use it, simply declare a method with the async prefix and use the wait inside it to wait for the call to complete.

eg

 async someMethod(){ result = await fetch(URL); // Do some request to any API. // Use the result after that knowing that you'll have it completed. } 

I hope this helps, at least in my opinion, it’s easier for me than using .then (), especially when you have to make several calls within the same method.

+1
source

Source: https://habr.com/ru/post/1239536/


All Articles