How to check internet connection in react native?

Viewed 3411

I want to check the internet connectivity when starting the app, then ask the user to connect to the internet if he doesn't

2 Answers

You should use the "@react-native-community/netinfo" library. NetInfo used to be part of the react-native, but then it got separated out of the core. If you want to observe network state changes just use the provided addEventListener method.

import NetInfo from "@react-native-community/netinfo";

NetInfo.fetch().then(state => {
    console.log("Connection type", state.type);
    console.log("Is connected?", state.isConnected);
});

const unsubscribe = NetInfo.addEventListener(state => {
    console.log("Connection type", state.type);
    console.log("Is connected?", state.isConnected);
});

// Unsubscribe
unsubscribe();
import NetInfo from '@react-native-community/netinfo';

NetInfo.fetch().then((state) => {
    console.log('Connection type', state.type);
    console.log('Is connected?', state.isConnected);
});

const unsubscribe = NetInfo.addEventListener((state) => {
    console.log('Connection type', state.type);
    console.log('Is connected?', state.isConnected);
});

Related