2

I am trying to make a fetch API call to a new Firebase instance with my React-Native app, but I am running into this error:

Possible Unhandled Promise Rejection (id: 0):
Network request failed
TypeError: Network request failed
    at XMLHttpRequest.xhr.onerror (http://localhost:8081/index.ios.bundle?platform=ios&dev=true&minify=false:25119:8)
    at XMLHttpRequest.dispatchEvent (http://localhost:8081/index.ios.bundle?platform=ios&dev=true&minify=false:10405:15)
    at XMLHttpRequest.setReadyState (http://localhost:8081/index.ios.bundle?platform=ios&dev=true&minify=false:26688:6)
    at XMLHttpRequest.__didCompleteResponse (http://localhost:8081/index.ios.bundle?platform=ios&dev=true&minify=false:26536:6)
    at http://localhost:8081/index.ios.bundle?platform=ios&dev=true&minify=false:26630:52
    at RCTDeviceEventEmitter.emit (http://localhost:8081/index.ios.bundle?platform=ios&dev=true&minify=false:9638:23)
    at MessageQueue.__callFunction (http://localhost:8081/index.ios.bundle?platform=ios&dev=true&minify=false:7493:34)
    at http://localhost:8081/index.ios.bundle?platform=ios&dev=true&minify=false:7375:8
    at guard (http://localhost:8081/index.ios.bundle?platform=ios&dev=true&minify=false:7306:1)
    at MessageQueue.callFunctionReturnFlushedQueue (http://localhost:8081/index.ios.bundle?platform=ios&dev=true&minify=false:7374:1)

The functions look like so:

 getNotes(username){
    username = username.toLowerCase().trim();
    var url = `https://myproject-6342.firebaseio.com/${username}.json`;
    return fetch(url).then((res) => res.json());
  },
  addNote(username, note){
    username = username.toLowerCase().trim();
    var url = `https://myproject-6342.firebaseio.com/${username}.json`;
    return fetch(url, {
      method: 'post',
      body: JSON.stringify(note)
    }).then((res) => res.json());
  }

What is going wrong here?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
user1072337
  • 12,615
  • 37
  • 116
  • 195

2 Answers2

3

The promise from the fetch API will reject with a TypeError when a network error occurs, which means you have to handle the error. Example:

function _handleError(errorMessage) {
  console.log(errorMessage);
}

fetch('https://api.github.com/users/octocat/repos').then(function(response) {
  if(response.ok) {
    return response.json();
  } else {
    _handleError(`Oops, something went wrong: ${response.status}, ${response.statusText}`);
  }
}).then(function(data) {
   if(data) {
     console.log('success', data);
   }
}).catch(function(error) {
  _handleError(`There has been a problem with your fetch operation: ${error.message}`);
});

More info here: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Checking_that_the_fetch_was_successful

1

Well in my case the emulator internet was not working, I followed the below thread to make that work. Android emulator not able to access the internet

Umair Raees
  • 129
  • 6