In this article

The First Steps Inform the customer of the new status. The NetInfo software suite What you need to know about using NetInfo Setting up a demonstration of network management using NetInfo and axios The NetInfo system will send out an alert to all registered users. addEventListener

Detect Network Reachability and Connection Type in React Native

This tutorial will show you how to use NetInfo to get connection details and axios to perform API calls in a React Native app when the network status changes unexpectedly.

It has quickly become a top concern for those of us working in mobile app development to think about consumers who may not have access to the internet or have a bad network connection but would still want to use your app. Adding resilience to your program so that it can function properly despite fluctuating network conditions will likely increase its popularity and stickiness.

The First Steps

Create a new React Native project by executing the following command before proceeding with the demonstration.

npx react-native init MyOfflineApp

The name of the project is "MyOfflineApp" in my example, but you may give it whatever name you choose.

Now, open up your Project folder and add the following npm packages:

cd MyOfflineApp
npm i --save @react-native-community/netinfo axios react-native-modal

Then, run the following command for iOS for linking libraries using CocoaPods:

npx pod-install

In the following sections, we’ll discuss how to prepare your app and your users for changes in network connectivity.

Inform the consumer of the new status

In order to get information from an application programming interface (API), users must have constant network connectivity. On the other hand, developer egos can't afford to assume that users will always have a reliable connection. Because of this, you need a strategy to deal with situations in which the user's internet connection drops while the app is getting data from the server if you want them to be able to use your mobile app at all times, regardless of connectivity.

First, you should inform the user that their device is not online; second, you should prepare a backup user interface to utilize until your internet connection is restored.

The NetInfo software suite

The NetInfo package reports the user's current network status and connection details. A user's current network type is also shown (WiFi, cellular, ethernet, and so on). If it is a cellular connection, netinfo will additionally provide the generation (2G, 3G, 4G), the cost (in terms of both battery life and money), and the quality of the connection.

What you need to know about using NetInfo

In order to use the NetInfo package, you must include the following lines of code in your component file:

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

Using addEventListener(), you may monitor the network for changes in state:

NetInfo.addEventListener(networkState => {
  console.log("Connection type - ", networkState.type);
  console.log("Is connected? - ", networkState.isConnected);
});

When a component is unmounted, the addEventListener() function returns a reference to its unsubscribe method.

When just a single snapshot of the current network state is needed, rather than constantly monitoring for updates, utilize the get() function.

NetInfo.fetch().then(networkState => {
  console.log("Connection type - ", networkState.type);
  console.log("Is connected? - ", networkState.isConnected);
});

Form of the network state object:

{
  type: "wifi",
  isConnected: true,
  isInternetReachable: true,
  isWifiEnabled: true,
  details: {...}
}

One of the following values may be used for the type key (network type).

  • none
  • unknown
  • cellular
  • wifi
  • bluetooth
  • ethernet
  • vpn
  • wimax
  • other

Take into account that the details property varies depending on the type property value. Information about the NetInfo API is available in the manual.

Setting up a demonstration of network management using NetInfo and axios

In this tutorial, we'll create a sample app that uses the random user API to generate a list of users.

To begin, at the very start of your component file, import the necessary packages:

import React, {useEffect, useState} from 'react';
import axios from 'axios';
import {
  View,
  StyleSheet,
  FlatList,
  Image,
  Text,
  Dimensions,
  SafeAreaView,
} from 'react-native';

Make a Person widget to provide details about a single user in the list. Adding an Image component to show the user's avatar and a few Text components to show their name and email address shouldn't be too difficult.

const User = ({name, email, avatar}) => (
  <View style={styles.user}>
    <Image source={{uri: avatar}} style={styles.avatar} />
    <View style={styles.info}>
      <Text style={styles.name}>{name}</Text>
      <Text style={styles.email}>{email}</Text>
    </View>
  </View>
);

Render the user list using the FlatList component within the Users component after retrieving the data from the API. Use the axios.get() function and give the API endpoint to initiate the network call.

Axios, as a point of reference, may be used to perform network queries to a publicly available application programming interface. A connection error message will be shown at the bottom of the screen using the react-native-modal package.

Get the users within the useEffect hook's callback, then save them to the users state variable. To show that data retrieval is in progress, you will additionally create a variable named isLoading

const Users = () => {
  const [isLoading, setLoading] = useState(false);
  const [users, setUsers] = useState([]);
  useEffect(() => {
    fetchUsers();
  }, []);
  const fetchUsers = () => {
    setLoading(true);
    axios
      .get('https://randomuser.me/api/?results=30')
      .then(({data}) => {
        const {results} = data;
        setUsers(results);
      })
      .finally(() => {
        setLoading(false);
      });
  };
  return (
    <SafeAreaView style={styles.container}>
      <FlatList
        onRefresh={fetchUsers}
        refreshing={isLoading}
        data={users}
        renderItem={({item: user}) => (
          <User
            name={`${user.name.first} ${user.name.last}`}
            email={user.email}
            avatar={user.picture.thumbnail}
          />
        )}
        keyExtractor={(user) => user.login.uuid}
      />
    </SafeAreaView>
  );
};
export default Users;

The component styles object is listed below:

const styles = StyleSheet.create({
  container: {
    ...StyleSheet.absoluteFillObject,
  },
  user: {
    width: Dimensions.get('screen').width - 32,
    alignSelf: 'center',
    marginVertical: 8,
    padding: 12,
    borderWidth: 1,
    borderColor: '#eee',
    borderRadius: 6,
    flexDirection: 'row',
    alignItems: 'center',
  },
  info: {
    marginLeft: 10,
  },
  avatar: {
    width: 60,
    height: 60,
    borderRadius: 100,
  },
  name: {
    color: '#424242',
    fontSize: 16,
    fontWeight: '600',
  },
  email: {
    marginTop: 6,
    color: '#888',
  },
});

You can now retrieve user information from the API and show it to the user.

The NetInfo system will send out an alert to all registered users. addEventListener

Our next topic will be a discussion of what to do with the user interface if the user loses network connectivity.

To begin, create a state variable called isOffline that may store a boolean value to indicate whether or not the user is currently offline. Include NetInfo. Listen for network status changes and refresh the isOffline value using addEventListener in the useEffect hook.

Please refer to the list below:

const Users = () => {
  // ...
  const [isOffline, setOfflineStatus] = useState(false);
  useEffect(() => {
    const removeNetInfoSubscription = NetInfo.addEventListener((state) => {
      const offline = ! (state.isConnected && state.isInternetReachable);
      setOfflineStatus(offline);
    });
    fetchUsers();
    return () => removeNetInfoSubscription();
  }, []);
  // ...
}

If the user is not currently online, an error message and a "retry" button will appear in a pop-up window (or "modal") anytime the is Offline condition is not true.