How to handle network failure in React-Native, when device not connected to network.
My scenario is am trying to connect some api, while fetching request if network is disconnected react-native throws network request failed error. how to handle this scenario to give the user best user experience.
How to handle Network request failed in a better way.
Use NetInfo like this:
// Check for network connectivity
NetInfo.isConnected.fetch().done((isConnected) => {
if ( isConnected )
{
// Run your API call
}
else
{
// Ideally load from local storage
}
});
Handle the exception using a catch block, from the catch block you can perform the action that handles the exception, may be a redirection or a state change to show the error
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) {
//perform the redirection to the network request slow page or set state to show error
}
});
This may happen because of 2 main things:
AndroidManifest.xml
or info.plist
)Just handle this case inside catch
:
try {
const response = fetch(request)
} catch (e) {
if (error.message === 'Network request failed') {
// retry or any other handling like showing alert
} else {
throw e;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With