Sam
Sam

Reputation: 30292

NetInfo usage pattern in React Native

I'm trying to create a robust pattern in my React Native app so that if Internet connection is not there, I won't make API calls but display a "Connection lost..." message.

I created the following util function and trying to incorporate it into my API calls using fetch but it doesn't seem to hit the then block after getting a response.

Here's the function that checks the connection:

import NetInfo from "@react-native-community/netinfo";

export const isConnectedToInternet = () => {

   NetInfo.fetch().then(state => {
      return state.isConnected;
    });
};

And here's how I'm trying to use it:

import { isConnectedToInternet } from '../my-utils';

export const someApiCall = () => {

   isConnectedToInternet()
      .then(result => {

         if(result) {
          
             return (dispatch) => fetch ('https://myapi/someendpoint', fetchOptionsGet())
                               .then(response => {

                                  // Process data...
                               })
         } else {
    
             Alert.alert('No Internet connection!');
         }
   })
};

Any idea why I'm not hitting the then block or suggestions to make this a robust pattern?

Upvotes: 0

Views: 1310

Answers (2)

A. Goodale
A. Goodale

Reputation: 1348

In mobile software, a best practice is to always try the remote API, and then handle the exception if there's no internet. The reachability APIs provided by iOS and Android are not always accurate - they need to poll to determine connectivity. So an app is better off always trying the fetch, even if it thinks the internet may be down, in case the device got connectivity restored since the last reachability check.

If you want to model some state that shows UI when the app thinks it's offline, you can do that using the NetInfo.addEventListener() function. There's a React hook for that too I think.

Upvotes: 0

Bogdan
Bogdan

Reputation: 34

If you want to have the then on your isConnectedToInternet you should then make it return a promise. Try something like this:

import NetInfo from "@react-native-community/netinfo";

export const isConnectedToInternet = () => {
    return new Promise((resolve, reject) => {
        NetInfo.fetch().then(state => {
            resolve(state.isConnected);
        }).catch(e => reject(e));
    })
};

Upvotes: 2

Related Questions