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

5

18

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

Constrict answered 28/4, 2016 at 23:14 Comment(1)
Have you found any solutions since this time?Bisayas
C
10

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
    }
});
Coccid answered 29/4, 2016 at 10:21 Comment(4)
NetInfo hasn't been fixed since 2016.Laktasic
@LingboTang the world has got progressively more depressing since 2016.. NetInfo is just trying to protect youClipped
@ComethTheNerd isConnected will always return false on iOS and it hasn't been fixed: github.com/facebook/react-native/issues/8615Laktasic
Hey , I want to show message whenever net disconnected . i don't want to call it in every api .Cryohydrate
S
1

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
      }
    });
Synecdoche answered 7/2, 2019 at 7:23 Comment(0)
H
1

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; 
  }
}
Hogback answered 30/6, 2021 at 16:34 Comment(0)
M
0

Use package in React i.e. npm i react-detect-offline import { Offline, Online } from 'react-detect-offline'; in your app and enclose value to be shown in Online mode under Online else Offline message like Network Disconnected <Online>Show Online values</Online> <Offline>Network Disconnected</Offline>

Maniple answered 8/7, 2020 at 6:32 Comment(0)
C
-1

The red screen only display in debug mode. To handle the error in case no Internet connection, can use try...catch block

     try {
        let response = await fetch(url, params);
    } catch (error) {
        
        console.error(error);
    }
Coppola answered 30/6, 2020 at 9:2 Comment(1)
The handle is not good enough, you catch all errors and not only network request failedHogback

© 2022 - 2024 — McMap. All rights reserved.