1

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 />
      );
    };
Aymen
  • 248
  • 3
  • 15

4 Answers4

0

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
},[])
shammi
  • 1,301
  • 1
  • 10
  • 25
  • doesn't work. i need to test internet connexion while the app is working. this code check it one time – Aymen Mar 25 '22 at 17:45
0

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

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.

Hamid khan
  • 105
  • 7
  • useEffect(()=>{ const unsubscribe = NetInfo.addEventListener(state => { if (!mountedRef.current) return null; setConnected(state.isInternetReachable) }); return unsubscribe; },[]); – Hamid khan May 30 '22 at 07:57
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 30 '22 at 10:21
0

Try to use this version of NetInfo:

yarn add @react-native-community/netinfo@6.2.0
Mustapha GHLISSI
  • 1,485
  • 1
  • 15
  • 16