Pratap Penmetsa
Pratap Penmetsa

Reputation: 1237

Auto update Net Info status in react-native

I am using https://github.com/react-native-community/react-native-netinfo to check network connection in my react-native app. How can fetch network connection automatically when Network is lost and the Network is back again?

Below is the code I using.

import React, { Component } from 'react';
import NetInfo from '@react-native-community/netinfo'
import { View, Text,StyleSheet,Dimensions } from 'react-native';
export default class NetStatus extends Component {

    constructor(props) {
        super (props)
        this.state = {
            isConnected:''
  };
}
  
  componentDidMount() {
    this.handleConnectivityChange()
  }

  componentWillUnmount() {
    this.handleConnectivityChange()
  }

  handleConnectivityChange(){
    NetInfo.fetch().then(isConnected => {
        this.setState({ isConnected:isConnected.isInternetReachable });
        console.log('isConnected : ', isConnected);
    })
  };
 
  render() {
    return (
        <View>
        {this.state.isConnected  === true ?
            null
           :(
             <View style={styles.container}>
                <Text style={{color:'#FFF'}}>
                You are not connected to internet....!
                </Text>
             </View>
           )
         }
         </View>
    );
  }
}

How can I get the network status without fetching every time when Network is lost and the Network is back again?

Upvotes: 1

Views: 1509

Answers (1)

senthil balaji
senthil balaji

Reputation: 628

You have to add a listener to NetInfo.

Following code can help you,

  const [networkState, setNetworkState] = useState(true);

  const onNetworkStateChange = (newState) => {
    setNetworkState(newState.isConnected);
    if (!newState.isConnected) {
      // do anything you want
    }
  };

  const initialCheck = () =>
    NetInfo.fetch().then((connectionInfo) => {
      setNetworkState(connectionInfo.isConnected);
    });

  useEffect(() => {
    initialCheck();
    NetInfo.addEventListener(onNetworkStateChange);
  }, []);

Upvotes: 2

Related Questions