Akrem Gomri
Akrem Gomri

Reputation: 11

In React Native how can I disable a button after being pressed. (useState not updating in time)

The problem is that I have a screen containing a button "se connecter" which means sign in, once that button is pressed, the application will navigate to a different screen (homeScreen).

enter image description here

now the problem is the following: If the user press on that button multiple times before the application navigates, the application will navigate to the homeScreen multiple times, meaning, the homeScreen Activity will get pushed to the tabs navigator stack as many times as it is pressed.

I tried using useState and once the button gets pressed, it sets to disabled, but that didn't work for me

this is the useState declaration: const [isPending, setIsPending] = useState(false);

this is the button:

<Button
  containerStyle={styles.loginContainer}
  style={styles.loginText}
  disabled={**isPending**}
  onPress={**onSignInPressed**}>
  Se connecter
</Button>

this is the function onSignInPressed:

const onSignInPressed= async (e) => { if(isPending) return;

console.log(isPending) // always returns false no matter what. setIsPending(true) // lots of work here and call to a fetch function to fetch some data endpoint

setIsPending(false) }

Upvotes: 0

Views: 178

Answers (1)

Info

Be clear in your question provide a link to a full mock file of your code. (Ajoute le code du fichier en entier pour qu'on puisse mieux t'aider)

What you can do

You don't have to add this line because once the Button is disabled, Events are not fired anymore

 if(isPending) return;

If it doesn't work, Take a break, read more about useState in the docs and about asynchronicity

Upvotes: 1

Related Questions