Issue with netinfo react native

2.5k Views Asked by At

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 />
      );
    };
4

There are 4 best solutions below

1
On

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
},[])
0
On

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 />
  );
};
2
On

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.

0
On

Try to use this version of NetInfo:

yarn add @react-native-community/[email protected]