React Native How to check Connection State

React Native How to check Connection State

Hello everyone, in this article we will talk about how to check device connection state dynamicaly in a react native application. We will show a message at the screen when connection lost and we will remove this message when connection stated back again.

Now Let's get started.

First we will import required library in our project.

import React, { Component } from 'react';
import {
  AppRegistry,
  Platform,
  StyleSheet,
  Text,
  View,
  Alert,
  ActivityIndicator ,
  NetInfo, // Especially we need this library
} from 'react-native';
We should initialize the checking when the program started. So we need to use componentDidMount() override function. Below code block will show you how to do it.

componentDidMount() {
//This code will run when program started.
}

We will add below code block to initializing and the first check of the connection state. If there is no internet connection and alert message will show up and. Also this will change the state of the program to show the message which is waiting for the internet connection.


componentDidMount() {
       NetInfo.getConnectionInfo().then((connectionInfo) => {
               this.setState({
                   connectionInfo: connectionInfo.type
               });

               console.log('Initial, type: ' + connectionInfo.type + ', effectiveType: ' + connectionInfo.effectiveType);

               if( connectionInfo.type == 'none' ){
                 Alert.alert("Error", "Program needs the internet connection to start...");
               }
             });
}

So what if the connection state changes during the normal operation of the program. To check this, we have to add a listener and this related listener will change the state to show the message which specify "There is no internet connection."

Below code block will do this. We should add this inside of componentDidMount() function after NetInfo initialization.


NetInfo.addEventListener(
        'connectionChange',
        this.handleFirstConnectivityChange
      );

And also we should add below code block and bind it at constructor to change state.


handleFirstConnectivityChange(connectionInfo) {
        this.setState({
            connectionInfo: connectionInfo.type
        })
        console.log('First change, type: ' + connectionInfo.type + ', effectiveType: ' + connectionInfo.effectiveType);
      }

At last our codes will be like below code block.


export default class App extends Component<{}> {

        constructor(props) {
        super(props);

        this.state = {
               connectionInfo : '',
               isSesionCorrect: false,
               isMaintenanceMode: false,
               isNeedForUpdate: false,
               errorTextForModes: '',
             };
         this.handleFirstConnectivityChange = this.handleFirstConnectivityChange.bind(this);
       }
    componentDidMount() {
                  
      NetInfo.getConnectionInfo().then((connectionInfo) => {
        this.setState({
            connectionInfo: connectionInfo.type
        })
        console.log('Initial, type: ' + connectionInfo.type + ', effectiveType: ' + connectionInfo.effectiveType);
        if( connectionInfo.type == 'none' ){
                 Alert.alert("Error", "Program needs the internet connection to start...");
               }
      });

      NetInfo.addEventListener(
        'connectionChange',
        this.handleFirstConnectivityChange
      );
    }

    handleFirstConnectivityChange(connectionInfo) {
        this.setState({
            connectionInfo: connectionInfo.type
        })
        console.log('First change, type: ' + connectionInfo.type + ', effectiveType: ' + connectionInfo.effectiveType);
      }

    render() {
        if( this.state.connectionInfo == 'none'   ){
            return (
             //Return the view that specify there is no internet connection.
             );
        }
    }

}

Above code block will initialize the checking of the connection state and at first and during the normal operation. We built a listener and then set the state via this related listener.

I used below view to specify there is no internet.


if( this.state.connectionInfo == 'none'   ){
       
        return (
              <View style={{flex: 1, paddingTop: 20}}>
              <Text
                      style={{ marginLeft: 10,  
                                    color: 'red', 
                                   fontSize:16, 
                                   fontWeight: 'bold', 
                                   textAlign: 'center' }}>

                         Waiting for the internet connection!

             </Text>
               <ActivityIndicator />

             </View>
             /*<View><Text>Yükleniyor...</Text></View>;*/
         );
    } else{

    }

Now we are ready to check connection state of the internet state.

That is all in this article.

Have a good checking internet connection state.

Burak Hamdi TUFAN


Tags


Share this Post

Send with Whatsapp

Post a Comment

Success! Your comment sent to post. It will be showed after confirmation.
Error! There was an error sending your comment. Check your inputs!

Comments

  • There is no comment. Be the owner of first comment...