skip to Main Content

I am showing an alert dialog using react native code in my android phone.

This will be shown when user clicks a button on the screen.

Alert.alert(
  title,
  message,
  [
    {
      text: buttonNegativeText,
      style: 'cancel',
      onPress: () => {
        onNegativePress();
      },
    },
    {
      text: buttonPositiveText,
      style: positiveStyle,
      onPress: () => {
        onPositivePress();
      },
    },
  ],
  {cancelable: cancelable},
);

};

And once user leaves the app for 10 seconds(for example), there is an event from native code which will logout the app. When app is getting logged out that means existing screen will be moved and new login screen will be shown.

Whats happening is, the alert dialog is still live in the new screen. i wanted to close the alert dialog when screen moves.

One thing, we can do is, we shall listen the event from native and close the dialog.

But is there a possibility when the current screen moves to other screen and existing screen’s alert screen closes automatically.

Not sure whether i am asking the correct question. Pls help.

2

Answers


  1. You can’t dismiss the native Alert programmatically https://github.com/facebook/react-native/issues/4928

    Login or Signup to reply.
  2. You can use useIsFocused

    import { useIsFocused } from '@react-navigation/native';
    
    const isFocused = useIsFocused();
     useEffect(() => {
     if (isFocused) {
        // Show the alert when the screen is focused
        Alert.alert('Screen is focused');
     } else {
        // Hide the alert when the screen is unfocused
        Alert.alert('Screen is unfocused');
     }
     // Clean up the alert when the component is unmounted or screen focus changes
     return () => {
      Alert.alert('Clean up');
     };
    }, [isFocused]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search