3

I've tried @react-native-community/netinfo to check the internet reachability. But the scenario I want to implement is, suppose if my device is connected to a wifi hotspot from another device and if that device's mobile data is turned off I want to show an offline toast.

componentDidMount() {
 NetInfo.addEventListener(status => {
  this.props.checkOnlineStatus(
    status.isConnected,
    status.isInternetReachable
  );
  this.setState({
    isConnected: status.isConnected,
    isInternetReachable: status.isInternetReachable
  });
 });
}

render() {
 if (!this.state.isInternetReachable && this.props.isOfflineNoticeVisible) {
  return <MiniOfflineSign />;
 }
 return null;
}

But in this case, when the mobile data of the other device is turned off, it doesn't handle the change.

Vinay N
  • 249
  • 1
  • 8
  • 32

3 Answers3

2

These connection types could help: https://github.com/react-native-community/react-native-netinfo#netinfostatetype

Otherwise:

Then to be sure, you are online just implement a fetch with timeout:

 export default function(url, options, timeout = 5000) {
      return Promise.race([
        fetch(url, options),
        new Promise((_, reject) => setTimeout(() => reject("timeout"), timeout)),
      ]);
    }

Then use it like this:

fetchWithTimeout(url, options)
        .then(resp => {
          if (resp.status === 200) {
            let json = resp.json().then(j => {
              return j;
            });
        })
        .catch(ex => {
          // HANDLE offline usage
          if (ex === "timeout") return true;
          //ANY OTHER CASE RETURN FALSE
          return false;
}
2

The non-deprecated way (using functional components) with the @react-native-community/netinfo package is now:

import React, { useEffect } from "react";
import NetInfo from "@react-native-community/netinfo";
  useEffect(() => {
    return NetInfo.addEventListener(state => {
      // use state.isInternetReachable or some other field
      // I used a useState hook to store the result for use elsewhere
    });
  }, []);

This will run the callback whenever the state changes, and unsubscribe when the component unmounts.

Karatekid430
  • 940
  • 11
  • 25
1

async function InternetCheck() {
    const connectionInfo = await NetInfo.getConnectionInfo();
    if (connectionInfo.type === 'none') {
        alert('PLEASE CONNECT TO INTERNET');
    } else {
            //navigate to page or Call API
    }
}
Israt Jahan Simu
  • 1,040
  • 13
  • 7
  • Unfortunately, it triggers 2 events, one with type='wifi' and then one with 'none'. This causes issues on our handlers, as it triggers side effects that they should not be triggered (for the 1st event which should not be there) – user2078023 Dec 09 '20 at 21:08