1110
1110

Reputation: 6839

How to make TouchableOpacity button to prevent multiple clicks

I have TouchableOpacity with event that I don't want to execute twice.

I tried to put in it's onPress event bool in state but this doesn't work as setting state is async and I can press button multiple times fast.

I also tried to set timer but this also doesn't work for me.

Is there any other way to prevent multiple press on button (some other similar component etc.)?

Upvotes: 1

Views: 6022

Answers (1)

Naisheel Verdhan
Naisheel Verdhan

Reputation: 5143

You do not need to setState to store values which do not reflect as UI changes.

You could directly have a this.flag instead of this.state.flag inside your React Class which you set on TouchableOpacity click. So, you can set this.flag without it being asynchronous operation involving a render cycle. It'll just be a flag which your component holds.

See example below:

class SomeComponent extends React.Component{
  constructor() {
   super();
   this.state = { ... }; // this does not need to store our flag
   this.touchableInactive = false; // this is not state variable. hence sync
  }

  onButtonClick () {
    if (!this.touchableInactive) {
      this.touchableInactive = true;
      // do stuff
    }
  }

      // similarly reset this.touchableInactive to false somewhere else
}

Upvotes: 4

Related Questions