How to deal with network failure in React-Native when the network is offline

How to deal with network failure in React-Native when the device is not connected to the network.

In my scenario, I am trying to connect some api, while fetching a request, if the network is disconnected, causes a network failure request response. how to deal with this scenario to give the user a better user interface.

How to cope with the network request failed.

enter image description here

+10
source share
3 answers

Use NetInfo as follows:

// Check for network connectivity NetInfo.isConnected.fetch().done((isConnected) => { if ( isConnected ) { // Run your API call } else { // Ideally load from local storage } }); 
+8
source

You can try this for error handling with fetch ()

 // Handling Internet Errors handleErrors(response) { if (!response.ok) { throw Error(response.statusText); } return response; } fetch(/*"url"*/) .then(this.handleErrors) .then(response => console.log("ok") ) .catch(error => console.log(error) ); 
0
source

const url = your url to be fetched ; fetch (url, {method: "GET", headers: header}). then (res => res.json ()). then (json => {console.log (json); this.setState ({data: json )});
}). catch (error => {if (error) {// redirect to the slow page of the network request or set the state to display the error}});

0
source

All Articles