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;
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With