React Native's NetInfo not capturing when WiFi is turned back on

Viewed 1869

I'm building a small component that will show a red strip that says No Connection. It works fine when I turn off wifi, the banner appears alright. When I turn the wifi back on, NetInfo doesn't seem to be getting the event and so the banner stays where it was.

The console log doesn't print anything when wifi is turned on, so I assume there's no update to netinfo.

Here's my OfflineNotice component:

import React, {useState, useEffect} from 'react';
import {View, StyleSheet, Dimensions, Text} from 'react-native';
import NetInfo from '@react-native-community/netinfo';

const {width} = Dimensions.get('window');

const OfflineNotice = () => {
  const [connected, setConnected] = useState(true);

  useEffect(() => {
    NetInfo.addEventListener((state) => {
      console.log(state);
      setConnected(state.isInternetReachable);
    });
  }, []);

  return (
    <View>
      {!connected && (
        <View style={styles.offlineContainer}>
          <Text style={styles.offlineText}>No Internet Connection</Text>
        </View>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  offlineContainer: {
    backgroundColor: '#b52424',
    height: 30,
    justifyContent: 'center',
    alignItems: 'center',
    flexDirection: 'row',
    width,
    position: 'absolute',
    top: 30,
  },
  offlineText: {
    color: '#fff',
  },
});

export default OfflineNotice;
2 Answers

if you are going with hooks, why don't you try useNetInfo() hook:

import {useNetInfo} from "@react-native-community/netinfo";

const YourComponent = () => {
  const netInfo = useNetInfo();

  return (
    <View>
      <Text>Type: {netInfo.type}</Text>
      <Text>Is Connected? {netInfo.isConnected.toString()}</Text>
    </View>
  );
};

I am using @react-native-community/netinfo version 6.0.0.

First time I got the latest version of it that is 9.3.0 In this version the the code was not listening for the network change.

const netInfo=useNetInfo();
useEffect(()=>{
console.log("network change", netInfo);
},[netInfo])

In android/build.gradle

ext{
.....
 androidXCore="1.6.0"
 }
Related