Vinay N
Vinay N

Reputation: 269

How to check the internet reachability in React-native?

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.

Upvotes: 3

Views: 8167

Answers (3)

Karatekid430
Karatekid430

Reputation: 1130

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.

Upvotes: 2

Patrick Loureiro
Patrick Loureiro

Reputation: 59

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;
}

Upvotes: 2

Israt Jahan Simu
Israt Jahan Simu

Reputation: 1110

async function InternetCheck() {
    const connectionInfo = await NetInfo.getConnectionInfo();
    if (connectionInfo.type === 'none') {
        alert('PLEASE CONNECT TO INTERNET');
    } else {
            //navigate to page or Call API
    }
}

Upvotes: 1

Related Questions