简体   繁体   中英

Detect internet connection in react native anywhere in screens

I'm confused on how can I show my customDialog whenever I don't have Internet connection to my app, Currently, I've only managed to show my customDialog within LoginScreen , I just want to show my custom dialog from different screen not only on LoginScreen whenever I don't have Internet connection, what is the best way to implement it? should I put CustomDialog each of the screen?

Someone have the idea to implement this? need help

在此处输入图像描述

screens/LoginScreen

  import NetInfo from "@react-native-community/netinfo";
  import CustomAlert from '../components/CustomAlert';
  const LoginScreen = ({navigation}) => {
  const [modalVisible, setModalVisible] = useState(false);
  const [internetCon, setNet] = useState(true);

  React.useEffect(()=>{
    checkInternetConnection();
}, [])

  function checkInternetConnection() {
    NetInfo.addEventListener(state =>{
      if (state.isConnected==false){
        setModalVisible(true);
        setNet(false); 
        console.log("Connection types", state.type);
        console.log("Your device appears to have no internet connectivity. Please check your connection settings and try again");
      }
      else{
        console.log("Connected to internet?", state.isConnected);
      }
    });
  }
  return (
    <ScrollView style={styles.container} >
      {internetCon ===false ?                    //Check if Internet Existt

        <CustomAlert 
        modalVisible={modalVisible} 
        setModalVisible={setModalVisible}
        title={'Message'}
        message={'Your device appears to have no internet connectivity. Please check your connection settings and try again'} 
        buttons={[{
          text: 'Retry',
          func: () => {checkInternetConnection();}
        }]}
    />
      :null}
    </ScrollView>
  );
};

export default LoginScreen;

navigation/AppStack.js

const Stack = createStackNavigator();
const Tab = createBottomTabNavigator();

const FeedStack = ({navigation}) => (
  <Stack.Navigator
  screenOptions={{
    headerShown: false
  }}>
    <Stack.Screen
      name="test"
      component={HomeScreen}
      options={{
        headerTitleAlign: 'center',
        headerTitleStyle: {
          color: '#2e64e5',
          fontFamily: 'Kufam-SemiBoldItalic',
          fontSize: 18,
        },
        headerStyle: {
          shadowColor: '#fff',
          elevation: 0,
        },
        headerRight: () => (
          <View style={{marginRight: 10}}>
            <FontAwesome5.Button
              name="plus"
              size={22}
              backgroundColor="#fff"
              color="#2e64e5"
              onPress={() => navigation.navigate('AddPost')}
            />
          </View>
        ),
      }}
    />
    <Stack.Screen
      name="HomeProfile"
      component={ProfileScreen}
      options={{
        title: '',
        headerTitleAlign: 'center',
        headerStyle: {
          backgroundColor: '#fff',
          shadowColor: '#fff',
          elevation: 0,
        },
        headerBackTitleVisible: false,
        headerBackImage: () => (
          <View style={{marginLeft: 15}}>
            <Ionicons name="arrow-back" size={25} color="#2e64e5" />
          </View>
        ),
      }}
    />

  </Stack.Navigator>
);



const AppStack = () => {
  const getTabBarVisibility = (route) => {
    const routeName = route.state
      ? route.state.routes[route.state.index].name
      : '';

    if (routeName === 'Chat') {
      return false;
    }
    return true;
  };

  return (
    <Tab.Navigator
      screenOptions={{
      headerShown: false
      }}
      tabBarOptions={{
        activeTintColor: '#2e64e5',
      }}>
      <Tab.Screen
        name="Home"
        component={FeedStack}
        options={({route}) => ({
          tabBarLabel: 'Home',
          // tabBarVisible: route.state && route.state.index === 0,
          tabBarIcon: ({color, size}) => (
            <MaterialCommunityIcons
              name="home-outline"
              color={color}
              size={size}
            />
          ),
        })}
      />
      <Tab.Screen
        name="Messages"
        component={MessageStack}
        options={({route}) => ({
          tabBarVisible: getTabBarVisibility(route),
          tabBarIcon: ({color, size}) => (
            <Ionicons
              name="chatbox-ellipses-outline"
              color={color}
              size={size}
            />
          ),
        })}
      />
    </Tab.Navigator>
  );
};

export default AppStack;

navigation/AuthProvider.js

export const AuthContext = createContext();
export const AuthProvider = ({children}) => {
  const [user, setUser] = useState(null);
  const [modalVisible, setModalVisible] = useState(false);


  return (
    <AuthContext.Provider
      value={{
        user,
        setUser,
        googleLogin: async () => {
          
          try {
            // Get the users ID token
            const Token  = await GoogleSignin.signIn();
            const {idToken} =  Token;
            console.log("Processing");
            console.log("ok");
            // Create a Google credential with the token
            const googleCredential = auth.GoogleAuthProvider.credential(idToken);              
            // Sign-in the user with the credential
            await auth().signInWithCredential(googleCredential)

            .catch(error => {
                console.log('Something went wrong with sign up: ', error);
            });
          } catch(error) {
            // console.log('Something went wrong with sign up: ', error);
            
          }
        }, 
      }}>
      {children}
    </AuthContext.Provider>
  );
};

Yo can try react-navigation modal: https://reactnavigation.org/docs/modal/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM