Reputation: 11
I have attached a snipped of a component called ConnectionChecker
which I have wrapped around all the screen navigations. I have used NetInfo
to check for the internet connectivity in the Connection Checker component, checking the connection for all the screens. But the network connectivity is not updated even though I used NetInfo.addEventListner for the same. The following is working for only one screen. But when I wrap the component around the Drawer Stack, it doesn't update the NetInfo
variable correctly through which I am checking the network connection.
import NetInfo, { useNetInfo } from '@react-native-community/netinfo';
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;
Upvotes: 1
Views: 5287
Reputation: 179
You can create external function to use everywhere like below;
import NetInfo from "@react-native-community/netinfo";
export function isConnected() {
return new Promise((resolve, reject) => {
NetInfo.fetch().then(state => {
console.log("Connection type", state.type);
console.log("Is connected?", state.isConnected);
if (state.isConnected) {
resolve();
}
else {
reject();
}
});
})
}
then, you can call this like this:
isConnected()
.then(() => console.log("has internet connection"))
.catch(() => console.log("no connection"))
so, you can import the connection check method to the required screens, components.
Upvotes: 3