i want to render specific screen when the app loose internet connexion, the attached code works one time when the app is opened from background.
any advices
import { useNetInfo } from '@react-native-community/netinfo';
export default () => {
const netInfo = useNetInfo();
useEffect(() => {
SplashScreen.hide();
}, []);
return netInfo.isConnected ? (
<SafeAreaProvider>
<Provider store={store}>
<App />
</Provider>
</SafeAreaProvider>
) : (
<NoInternet />
);
};
try this
useEffect(() => {
NetInfo.fetch().then(state => {
console.log("Connection type", state.type);
console.log("Is connected?", state.isConnected);
if(state.isConnected==false) naviagtion.navigate("yourscreenname")
});
const unsubscribe = NetInfo.addEventListener(state => {
console.log("Connection type", state.type);
console.log("Is connected?", state.isConnected);
setConnectionStatus(state.isConnected)
});
return unsubscribe
},[])
I would test for reachability instead of connection. Something like this should work. When you first check, the current reachability will return null. Instead of flashing with the no internet view, I think it is best to default that to true.
import { useNetInfo } from '@react-native-community/netinfo';
export default () => {
const netInfo = useNetInfo();
const [reachable, setReachable] = useState(true);
useEffect(() => {
SplashScreen.hide();
const unsubscribe = NetInfo.addEventListener(state => {
setReachable(state.isInternetReachable == null? true :
state.isInternetReachable)
});
return unsubscribe
}, []);
return reachable ? (
<SafeAreaProvider>
<Provider store={store}>
<App />
</Provider>
</SafeAreaProvider>
) : (
<NoInternet />
);
};
Take state variable for internet connection connection in context or redux, i have implemented it in many apps like this. try to use following code.