13

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?

Luis Rizo
  • 2,009
  • 4
  • 15
  • 34

1 Answers1

19

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();
}
TheJizel
  • 1,864
  • 1
  • 15
  • 14
  • Where do you define this.alertPresent? in the state? – Luis Rizo Mar 03 '17 at 05:23
  • 1
    @LuisRizo I actually didn't make it a state variable because I didn't want it to trigger re-render. But you can define it in the `constructor()` if you want. – TheJizel Mar 03 '17 at 13:23
  • Yeah I was thinking about it being either in a state or a store would cause re-rendering, I didn't know you could set variables like that, Thank you very much! – Luis Rizo Mar 03 '17 at 14:24
  • Thanks, this actually works. I was having problem with setting state inside the render method, and apparently this solved it. – Eddie Teixeira Jan 14 '19 at 22:37
  • 1
    @TheJizel I want to display alert in `render` method, like when user types in TextInput, and it's invalid. I have to show alert in that case. But render method is called twice so it's showing two alerts. That variable thing is not helping either. When that `CheckInternet` function gets called two time, variable value was still old. – Rahul Sagore Jul 11 '19 at 09:13