'How to check the internet connection in react native
I m working on react native project, I m using @react-native-community/netinfo package to check the internet status. It will work to me, but I have a doubt, if a person using internet connection with wifi, but the wifi device does not connect to the internet, then how to find that.?
Solution 1:[1]
You can use the isInternetReachable
to check that.
Here's a working code snippet that I'm using in my projects.
React.useEffect(() => {
const unsubscribe = NetInfo.addEventListener(state => {
console.log('Connection type', state.type)
console.log('Is Internet Reachable?', state.isInternetReachable)
if (connected !== state.isInternetReachable)
setConnected(state.isInternetReachable)
})
return () => unsubscribe()
}, [connected])
Solution 2:[2]
It seems this question is all over stackoverflow and no one seems to look at other existing answers.
You should use the "@react-native-community/netinfo" library. NetInfo used to be part of the react-native, but then it got separated out of the core. If you want to observe network state changes just use the provided addEventListener method.
import NetInfo from "@react-native-community/netinfo";
NetInfo.fetch().then(state => {
console.log("Connection type", state.type);
console.log("Is connected?", state.isConnected);
console.log("Is reachable?", state. isInternetReachable);
});
const unsubscribe = NetInfo.addEventListener(state => {
console.log("Connection type", state.type);
console.log("Is connected?", state.isConnected);
console.log("Is reachable?", state. isInternetReachable);
});
// Unsubscribe
unsubscribe();
Solution 3:[3]
import NetInfo from "@react-native-community/netinfo";
useEffect(() => {
const removeNetInfoSubscription = NetInfo.addEventListener((state)={
const offline = !(state.isConnected && state.isInternetReachable);
console.log(offline);
});
return () => removeNetInfoSubscription();
}, []);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | twboc |
Solution 3 |