I want react-native Alert.alert to close automatically after some time, so is this possible?

Viewed 37

I am using react-native Alert.alert, that is, when I press the back button on android, the Alert opens, and I also have a PasscodeScreen, the screen pops up in 5 minutes if nothing is done, and it stays on the Alert, but the alert needs to be closed, how can I do that?

enter image description here

1 Answers

Assuming you have a setState (called setAlert) to update the text displayed in the Alert

 const screen = () => {
    const [alertText, setAlert] = useState(null); 
             
    useEffect(()=>{
           
    if(alertText)
      {
       Alert.alert(
         "Alert Title",
          alertText);
       }
            
      setTimeout(() => {
          setAlert(null);
         }, 2000);
     },[alertText]);
            
            
     return (<Button onClick={()=>setAlert("Hi, I am an alert")}/>);
    
}

That's the logic that you need to follow: So let's say you are displaying the alert when the button is clicked. therefore, the useEffect will be called, and will display the alert, but then in 2 seconds the alert will be cleared.

Related