react-native: how to handle network request failed error?

I have a form and want to send it to a server and get a response so I wrote this:

submitForm = async () => {
  fetch("www.somewhere.com", {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(some_data)
  })
  .then((response) => response.json())
  .then((responseJson) => {
     // do something
  })
  .catch((error) => {
      this.setState({server_error: "request failed try again."});
  });
};

But It seems that my catch doesn’t work correctly because if the request fails I get an error from react native like this:

TypeError: Network request failed at XMLHttpRequest.xhr.onerror (C:\Archive\code\current\native\melcom\node_modules\react-native\Libraries\vendor\core\whatwg-fetch.js:504)

Note that I’m not struggling with http or https, I just want to provide a nice error to the user if the request fails due to the internet connection, wrong API, etc. instead of getting react native error.

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Reactions: 7
  • Comments: 18

Most upvoted comments

error.message this.state.error:error.message

Have you found a solution for this? I am having the same error.