react-nativereact-native-community-netinfo

React native screen isn't showing anything after using netinfo package


I'm coding in react native and everytime I try to run my project the screen doesn't show anything. It looks like there is an error within my code but I don't know the problem. Can someone read my code then show me what the problem is?

My code so far is:

// Note the additional import of useEffect
import React, { useState, useEffect,  useRef  } from 'react';
import { TouchableOpacity, Button, Text, View, StyleSheet } from 'react-native';
import * as WebBrowser from 'expo-web-browser';
import Constants from 'expo-constants';
import { Platform } from 'react-native';
import * as TaskManager from 'expo-task-manager';
import NetInfo from '@react-native-community/netinfo';
import { AppState } from 'react-native';





export default function App() {
  const [result, setResult] = useState(null);
  const [isConnected, setIsConnected] = useState(false);


  const _handlePressButtonAsync = async () => {
    let result = await WebBrowser.openBrowserAsync('https://quirkymehub.com');
    setResult(result);
  };

  const myFunction= () => {
    useEffect(() => {
      NetInfo.fetch().then(state => {
        if (state.isConnected) {
          useEffect(() => {
            _handlePressButtonAsync();
           }, []);
        } else {
          console.log('Internet is not connected');
          checkInternetConnection();
      
        }
      });
   }, []);
  };








  return (
    <View style={styles.container}>
      <Text>Website will open automatically</Text>
      <Text>{result && JSON.stringify(result)}</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
  },
});

I think the error is in the netinfo part in the beginning. I'm not sure why my screen isn't loading.


Solution

  • useEffect should not be inside myFunction, also there is no need to put another useEffect if network state is connected

    your code should look like

    useEffect(() => {
          NetInfo.fetch().then(state => {
            if (state.isConnected) {
              _handlePressButtonAsync();
            } else {
              console.log('Internet is not connected');
              checkInternetConnection();
            }
          });
       }, []);