Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does fetch return a weird hash of integers?

I'm using fetch API with React Native.

My response follows a normal format of {"message": "error here"} if the status is >= 400, which I will show in a native popup.

I'm trying to call response.json() after detecting a failure, but it keeps putting everything in a weird format...

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

For whatever reason... the actual response I want is located in _65... I have no idea what these random keys are.

So currently I'm having to access it via _bodyText, but I assume that is wrong because it's 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);
    }
  };

})();
like image 605
Tallboy Avatar asked Dec 31 '15 01:12

Tallboy


1 Answers

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

like image 55
Tallboy Avatar answered Oct 19 '22 23:10

Tallboy