Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent multiple Alerts in React Native?

Is there a way to tell if there was an Alert.alert() already on the screen before sending another one?

I have this function:

CheckInternet(){
  if(this.props.json.undefined){
    Alert.alert("Check your internet connection");
  }
}

ComponentDidUpdate(){
  this.CheckInternet();
}

The thing is that I have other things being done inside that function, I just wrote the relevant code, so I cannot take the CheckInternet function outside ComponentDidUpdate.

The problem is that the component updates twice after getting the json, therefore, sending that alert twice. I would like to prevent having two alerts at the same time by using a condition that would let me know if there is an alert on the screen already or not. I don't seem to find anything like that in the Alert documentation. Any ideas?

like image 629
Luis Rizo Avatar asked Mar 02 '17 22:03

Luis Rizo


1 Answers

Try this:

CheckInternet(){
    if (!this.alertPresent) {
        this.alertPresent = true;
        if (this.props.json.undefined) {
            Alert.alert("", "Check your internet connection", [{text: 'OK', onPress: () => { this.alertPresent = false } }], { cancelable: false });
        } else {
            this.alertPresent = false;
        }
    }
}

ComponentDidUpdate(){
  this.CheckInternet();
}
like image 84
TheJizel Avatar answered Sep 23 '22 15:09

TheJizel