Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle network failure in React-Native, when network is off

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.

enter image description here

like image 347
rakesh r Avatar asked Apr 28 '16 23:04

rakesh r


3 Answers

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
    }
});
like image 167
Ryan Marshall Avatar answered Oct 25 '22 22:10

Ryan Marshall


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
      }
    });
like image 26
Nandagopan PB Avatar answered Oct 26 '22 00:10

Nandagopan PB


This may happen because of 2 main things:

  1. Wrong definition about networks request (AndroidManifest.xml or info.plist)
  2. Interruption while streaming the response or very slow internet connection, or other same reasons...

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; 
  }
}
like image 1
Idan Avatar answered Oct 25 '22 22:10

Idan