React Native Managing network connection in 10 minutes

React Native network connection Android Ios Application

In this blog, you will learn how to gracefully handle network connection state changes in a React Native app by utilizing NetInfo for information about network connection and Axios to make network requests to a public API.

For those of us who are involved in mobile app building, it has rapidly become a priority to consider users who may not have access to the internet or have a poor network connection … but still want to access your application. Making your app resilient in the face of unknown connectivity can greatly improve user experience and consequently, user retention.

Getting started 

Create a basic React Native app

Before we can dive into our demo, we must first create a React Native project by running the following command:

npx react-native init RNNetwork

In my example, the name of the project is “RNNetwork,” but you can change it per your preference.

Next, go into the Project folder and install the required npm packages:

cd RNNetwork
npm i --save @react-native-community/netinfo axios react-native-modal 
   or 
yarn add @react-native-community/netinfo axios react-native-modal

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

npx pod-install ios

NetInfo package

The NetInfo the package provides information about the user’s active network connection and connectivity status of their mobile device. It also identifies the user’s current network type (WiFi, cellular, ethernet, and so on). If the connection is cellular, then netinfo will also return the generation type (2G, 3G, 4G), as well as how expensive the connection is in terms of battery consumption and monetary value.

The network state object has the following shape:

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

The type key (network type) can be one of the following values.

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

Note that the details property is different for each value of the type property. You can find more details on the NetInfo API in the documentation.

  • Open App.js and paste this code :
import React, {
    useEffect,
    useState
} from 'react';
import axios from 'axios';
import {
    View,
    StyleSheet,
    FlatList,
    Image,
    Text,
    Dimensions,
    SafeAreaView,
    TouchableOpacity
} from 'react-native';
import Modal from 'react-native-modal';
import NetInfo from "@react-native-community/netinfo";

const App = () => {
    const [isOffline, setOfflineStatus] = useState(false);
    const [isLoading, setLoading] = useState(false);
    const [users, setUsers] = useState([]);

    useEffect(() => {
        const removeNetInfoSubscription = NetInfo.addEventListener((state) => {
            const offline = !(state.isConnected && state.isInternetReachable);
            setOfflineStatus(offline);
        });

        fetchUsers();

        return () => removeNetInfoSubscription();
    }, []);

    const fetchUsers = () => {
        setLoading(true);
        axios
            .get('https://picsum.photos/v2/list?page=0&limit=30')
            .then(({
                data
            }) => {
                setUsers(data);
            })
            .finally(() => {
                setLoading(false);
            });
    };

    const Button = ({
        children,
        ...props
    }) => ( <
        TouchableOpacity style = {
            styles.button
        } {
            ...props
        } >
        <
        Text style = {
            styles.buttonText
        } > {
            children
        } < /Text> <
        /TouchableOpacity>
    );

    const NoInternetModal = ({
        show,
        onRetry,
        isRetrying
    }) => ( <
        Modal isVisible = {
            show
        }
        style = {
            styles.modal
        }
        animationInTiming = {
            600
        } >
        <
        View style = {
            styles.modalContainer
        } >
        <
        Text style = {
            styles.modalTitle
        } > Connection Error < /Text> <
        Text style = {
            styles.modalText
        } >
        Oops!Looks like your device is not connected to the Internet. <
        /Text> <
        Button onPress = {
            onRetry
        }
        disabled = {
            isRetrying
        } >
        Try Again <
        /Button> <
        /View> <
        /Modal>
    );

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

    return ( <
        SafeAreaView style = {
            styles.container
        } >
        <
        FlatList onRefresh = {
            fetchUsers
        }
        refreshing = {
            isLoading
        }
        data = {
            users
        }
        renderItem = {
            ({
                item
            }) => ( <
                User name = {
                    item.author
                }
                avatar = {
                    item.download_url
                }
                />
            )
        }
        keyExtractor = {
            (item, index) => index.toString()
        }
        /> <
        NoInternetModal show = {
            isOffline
        }
        onRetry = {
            fetchUsers
        }
        isRetrying = {
            isLoading
        }
        /> <
        /SafeAreaView>
    );
};

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',
    },
    modal: {
        justifyContent: 'flex-end',
        margin: 0,
    },
    modalContainer: {
        backgroundColor: '#fff',
        paddingHorizontal: 16,
        paddingTop: 20,
        paddingBottom: 40,
        alignItems: 'center',
    },
    modalTitle: {
        fontSize: 22,
        fontWeight: '600',
    },
    modalText: {
        fontSize: 18,
        color: '#555',
        marginTop: 14,
        textAlign: 'center',
        marginBottom: 10,
    },
    button: {
        backgroundColor: '#000',
        paddingVertical: 12,
        paddingHorizontal: 16,
        width: '100%',
        alignItems: 'center',
        marginTop: 10,
    },
    buttonText: {
        color: '#fff',
        fontSize: 20,
    },
});
export default App;

Android 

For android network permission flow this step

  • Open AndroidManifest.xml and add permission android/app/src/main/AndroidManifest.xml
   <uses - permission android: name = "android.permission.SYSTEM_ALERT_WINDOW" / >
   <uses - permission android: name = "android.permission.ACCESS_NETWORK_STATE" / >

 

Conclusion

In this guide, we reviewed the NetInfo library and a simple use case for handling network connection state. For further practice, you could look into ways of making the network connection state available to all components (global) using Context API or a third-party library like Redux.

Hope this tutorial saves your time and makes Network integration easy in react native. If it helps you in any way, don’t forget to love! Thanks :)

About the author
Code solution

info@codesolution.co.in

Discussion
  • 0 comments

Add comment To Login
Add comment