How to check internet connection in React Native application for both iOS and Android?

后端 未结 7 2214
孤城傲影
孤城傲影 2021-02-07 12:52

I have a React Native application and I\'m seeking to add functionality that checks if there is an active internet connection when the app first starts up, and continuously ther

相关标签:
7条回答
  • 2021-02-07 13:37

    It seems this question is all over stackoverflow and no one seems to look at other existing 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();
    
    0 讨论(0)
提交回复
热议问题