4

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;
Varun Joshi
  • 599
  • 2
  • 9
  • 24
  • can you console in your useEffect is reached ? because event listener will get destroy when unmount. you should put the listener in a side like App.js or index to always get updates – anthony willis muñoz Oct 15 '20 at 09:52
  • I know this is a bit old, but did you find the solution? – sina farbod Apr 24 '21 at 14:07
  • @sinafarbod nah I just used an npm module: https://www.npmjs.com/package/react-native-offline – Varun Joshi Apr 26 '21 at 09:42
  • Hey @VarunJoshi, I used both `@react-native-community/netinfo` and `react-native-offline` to create an `OfflineNotice` but none of them works. Can you assist me here.? – Kartikey Apr 04 '22 at 05:59

2 Answers2

0

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>
  );
};
Cristian Riță
  • 561
  • 3
  • 13
0

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"
 }
Pravin Ghorle
  • 606
  • 7
  • 7