Home > Software engineering >  How to use UseEffect for log out?
How to use UseEffect for log out?

Time:12-29

//Logout screen

import {Alert} from 'react-native';
import {useEffect} from 'react';
import {useIsFocused} from '@react-navigation/native';
const Logout = props => {
  const Logout1 = () => {
    const isFocused = useIsFocused();
    Alert.alert('Logout', 'Are you sure you want to logout?', [
      {
        text: 'Cancel',
        onPress: () =>
          props.navigation.navigate(
            'Tabs',

            {
              screen: 'HomeScreen',
            },
          ),
      },
      {text: 'Yes', onPress: () => props.navigation.navigate('Login')},
    ]);
  };
  useEffect(() => {}, [useIsFocused(), Logout1()]);
};
export default Logout;

I am expecting 1 time

 Alert.alert

but it is poping 2 time 1=> When clicking on Logout in Bottom Tab 2=> When i pressed cancel and navigate me to the another screen and poping up again

CodePudding user response:

You have to use isFocused in useEffect

import { Alert } from 'react-native';
import { useEffect } from 'react';
import { useIsFocused } from '@react-navigation/native';
const Logout = props => {
  const isFocused = useIsFocused(); // ----- edit
  const Logout1 = () => {
    Alert.alert('Logout', 'Are you sure you want to logout?', [
      {
        text: 'Cancel',
        onPress: () =>
          props.navigation.navigate(
            'Tabs',

            {
              screen: 'HomeScreen',
            },
          ),
      },
      { text: 'Yes', onPress: () => props.navigation.navigate('Login') },
    ]);
  };
  useEffect(() => {Logout1() }, [isFocused]); // ----- edit
};
export default Logout;
  • Related