NetInfo.isConnected.addEventListener only works in root componentDidMount
See original GitHub issueIs this a bug report?
Yes
Have you read the Contributing Guidelines?
Yes
Environment
Android only
Environment: OS: macOS Sierra 10.12.6 Node: 8.9.1 Yarn: 1.3.2 npm: 5.5.1 Watchman: 4.9.0 Xcode: Xcode 9.2 Build version 9C40b Android Studio: 3.0 AI-171.4443003
Packages: (wanted => installed) react: 16.2.0 => 16.2.0 react-native: 0.53.3 => 0.53.3
Steps to Reproduce
NetInfo.isConnected.addEventListener is not being registered unless on the root App.js component on componentDidMount
.
(Write your steps here:)
- Under your App.js file, create an event listener for NetInfo. Note that this works just fine.
- Create a child component (class component in my case) that renders in App.js
- Under the child component in the
componentDidMount
orcomponentWillMount
, create an event listener. - The listener here on your child component will never be called.
Expected Behavior
Expected the same functionality for registering an event listener on NetInfo to be the same no matter where it is called in the app.
Actual Behavior
The function specified in NetInfo.isConnected.addEventListener
never gets called on android unless it is in componentDidMount
on App.js.
Reproducible Demo
Snippet of App.js containing the child component:
class App extends React.Component {
//This works just fine if uncommented:
// componentDidMount() {
// NetInfo.isConnected.addEventListener(
// 'connectionChange',
// isConnected => {
// console.log('Connectedxc: ', isConnected);
// }
// );
// }
render() {
return (
<NetworkStatusProvider>
<Text>Some text</Text>
</NetworkStatusProvider>
);
}
}
And in the NetworkStatusProvider:
import {NetInfo} from 'react-native';
class NetworkStatusProvider extends React.Component {
componentDidMount() {
NetInfo.isConnected.addEventListener(
'connectionChange',
(value) => {
console.log('Expected to see value logged: ', value);
}
);
}
render() {
return this.props.children;
}
}
Issue Analytics
- State:
- Created 6 years ago
- Reactions:7
- Comments:9 (1 by maintainers)
Top GitHub Comments
In my experience the
NetInfo.isConnect
returns offline for Android (when I’m online)My workaround is to use
NetInfo.isConnected.fetch
. But not sure of its efficiency, though, since it gets called every time it mounts.