Reputation: 11
I am looking for alternative APIs of NetInfo. I have been trying to use NetInfo API as well as react-native-offline (which uses NetInfo behind the scenes) to check constantly if the user is connected to the internet or not in the app and render network error screen based on that. We are using drawer stack for screens and our app is running on react-native "^0.64.1". But the NetInfo isn't working properly. When the app starts, it detects the internet connection correctly but then if we switch the connection type or disconnect fro app, the state is not updating. I am using useNetInfo() hook to access the states of internet. But the value is not refreshing. The code is attatched here.
import React from 'react';
import NoInternetScreen from './NoInternetScreen';
const ConnectionChecker = ({ children }: { children: any }) => {
const netInfo = useNetInfo();
console.log('NetInfo is: ', netInfo.isConnected);
console.log('NetInfo type: ', netInfo.type);
return netInfo.isConnected ? (
children
) : (
<>
<NoInternetScreen />
</>
);
};
export default ConnectionChecker;
I am wrapping the drawer stack with . Since NetInfo is not refreshing I am trying to find the alternatives of NetInfo. So are there any alternatives for NetInfo which can be used to check the network connection and which work for react-native 0.64.1 ?
Upvotes: 0
Views: 1646
Reputation: 2359
You can try @react-native-community/netinfo
.
import NetInfo from "@react-native-community/netinfo";
const [isConnected, setIsConnected] = useState(true);
NetInfo.fetch().then(state => {
if (state.isConnected && state.isInternetReachable) {
setIsConnected(true);
} else {
setIsConnected(false);
}
});
useEffect(() => {
const unsubscribe = NetInfo.addEventListener((state) => {
if (state.isConnected && state.isInternetReachable) {
setIsConnected(true);
} else {
setIsConnected(false);
}
});
if (isConnected) {
} else {
unsubscribe();
}
return () => {
unsubscribe();
};
}, []);
Upvotes: 1