Currently, there is an ongoing issue related to this topic on React Native's GitHub page.
You can find more details in the discussion, but essentially, the fetch
method always returns false
. However, you can implement a workaround by monitoring the connection changed event.
Here is an example code snippet from the discussion:
componentDidMount() {
NetInfo.isConnected.addEventListener('change', this.handleConnectionChange);
NetInfo.isConnected.fetch().done(
(isConnected) => { this.setState({ status: isConnected }); }
);
}
componentWillUnmount() {
NetInfo.isConnected.removeEventListener('change', this.handleConnectionChange);
}
handleConnectionChange = (isConnected) => {
this.setState({ status: isConnected });
console.log(`is connected: ${this.state.status}`);
}
Note:
It appears that progress has been made on addressing this issue in recent commits.
Additionally, the event type change
has now been renamed to connectionChange
. Here is the updated workaround code:
componentDidMount() {
NetInfo.isConnected.addEventListener('connectionChange', this.handleConnectionChange);
NetInfo.isConnected.fetch().done(
(isConnected) => { this.setState({ status: isConnected }); }
);
}
componentWillUnmount() {
NetInfo.isConnected.removeEventListener('connectionChange', this.handleConnectionChange);
}
handleConnectionChange = (isConnected) => {
this.setState({ status: isConnected });
console.log(`is connected: ${this.state.status}`);
}
Update:
The event type change
is no longer recommended. It is advised to use the connectionChange
event type instead.