NadavL
NadavL

Reputation: 400

Ways to ensure an onPress function is only called once for clickable?

I've tried using a semaphore like concept:

This normally works, but in extreme conditions when the clickable is spammed, it appears some sort of a race condition happens between all the events, and sometimes I get two executions of the function logic.

Code example for those who need visuals:

<ClickableComponent onPress={() => { 
     if (this.state.clicked) return;
     this.state.clicked = true;
     // Execute logic here
     // This logic sometime gets executed twice when the clicking is fast enough
     this.state.clicked = false;
     }}
} />

Any ideas on different ways to approach it?

Upvotes: 0

Views: 375

Answers (1)

Samuli Hakoniemi
Samuli Hakoniemi

Reputation: 19049

You can't set state directly. And you have to execute logic in the callback of setState.

<ClickableComponent onPress={() => { 
  if (this.state.clicked) return;

  this.setState({ clicked: true }, () => {
    // Execute logic here
    this.setState({ clicked: false });
  });
} />

Upvotes: 2

Related Questions