rishabhbhatia / react-native-awesome-alerts

Awesome alerts for React Native, works with iOS and Android.
MIT License
525 stars 71 forks source link

Native Alert is auto dismissed when Awesome Alert is closed #74

Closed kelokchan closed 4 years ago

kelokchan commented 4 years ago

I'm currently using AwesomeAlert as a spinner. I have an API call that will set show to false to close the AwesomeAlert fire Alert.alert() whenever the response is received. The problem is, whenever the spinner is closed, my successful Alert will be dismissed altogether. Any idea why?


import { Alert } from 'react-native';

const Login = ({ navigation }) => {
  const [visible, setVisible] = useState(false);

  const onSubmit = (values) => {
      setVisible(true);
      doAPICall().then(() => {
            setVisible(false);
           Alert.alert('Success') // This alert will be automatically dismissed when visible is false
      })
  };

  return (
    <Container>
      <Spinner show={isLoading} /> // Awesome Alert component
          <Button my={10} onPress={handleSubmit(onSubmit)}>
            Submit
          </Button>
    </Container>
  );
};

export default Login;
rishabhbhatia commented 4 years ago

put Alert.alert('Success') in a setTimeout with 1-second delay and try what happens.

kelokchan commented 4 years ago

That would work. Is there a better, less hacky way?

rishabhbhatia commented 4 years ago

@kelokchan Kelok the problem lies in these two lines

setVisible(false);
Alert.alert('Success')

State updates are async and here you're trying to show an Alert while the previous Modal isn't dismissed yet. The setTimeout call was for my confirmation. In terms of pseudo-code, you want to hide the alert, and after it is dismissed show another alert. The classic way of doing it with setState was to use the callback, you'd write like setState({ visible: false }, () => do something). Look at useEffect hook and you should be able to google your way towards a solution.