Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react native check internet connection with NetINFO

Tags:

react-native

I implement checking internet on my react-native v0.49 app. I'm using NetInfo of react-native. I add eventListener when any change happen it will call to function. but when i test it in emulator and real device I get only the first change but if I disconnect from Wifi I don't see any change.

internetConnectionPopUp

    import React, { Component } from 'react';
import {
    View,
    Text,
    NetInfo
} from 'react-native';

// styles
import { style } from './style';
import { globalStyle } from '../../assets/styles/globalStyle';

// redux
import {connect} from 'react-redux';
import * as actions from '../../actions';

class InternetConnectionPopUp extends Component {
    constructor(props){
        super(props);
        this.state = { 
            connectionInfo : ''

         }
         this.handleFirstConnectivityChange = this.handleFirstConnectivityChange.bind(this);

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

      }

    componentWillMount () {
        NetInfo.getConnectionInfo().then((connectionInfo) => {
            this.setState({
                connectionInfo: connectionInfo.type
            })
            //console.log('Initial, type: ' + connectionInfo.type + ', effectiveType: ' + connectionInfo.effectiveType);
          });

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




    render() {


        return (
            <View>
                <Text> ComponentName component </Text>
                <Text> { this.state.connectionInfo } </Text>
            </View>    
        );
    }
}


export default InternetConnectionPopUp;
like image 964
Manspof Avatar asked Oct 19 '17 15:10

Manspof


1 Answers

I could reproduce your error and it works for me changing componentWillMount to componentDidMount. I think React is having an internal error calling to this.setState because component is not mounted yet (so it can re-render anything).

Hope it helps :)

like image 98
Jhinel Arcaya Avatar answered Nov 10 '22 17:11

Jhinel Arcaya