weirdcoder
weirdcoder

Reputation: 31

How to disable/enable a button efficiently based on countdown timer in React Native?

I am making a login screen, in which user has to verify his phone number, and when he clicks on 'RESEND OTP(one time password)' and OTP is sent to his phone.

But, as soon as 'Resend OTP' button is clicked, it should get disabled for 30 seconds, and a countdown should be displayed, and as soon as it reaches 0, button should get enabled again. And the process should reset, as in he should be able to click on it again, and time should start again from 30, and so on.

componentDidUpdate() {
    if (this.state.timer === 1) {
      clearInterval(this.interval);
    }
  }

  componentWillUnmount() {
    clearInterval(this.interval);
  }

 resendOtp = () => {
    this.setState({
      isButtonDisabled: true,
    });

    this.interval = setTimeout(() => { return this.setState({
      isButtonDisabled: false,
    }); }, 10000);

    this.interval = setInterval(
      () => { return this.setState((prevState) => {
        return { timer: prevState.timer - 1 }; }); },
      1000
    );

    this.requestOtp();
  }

<Text style={styles.text}>{this.state.timer}</Text>
<TextButton
 title="Resend OTP"
 onPress={this.resendOtp}
 disabled={this.state.isButtonDisabled}
/>

Upvotes: 2

Views: 3862

Answers (2)

Vijay Kahar
Vijay Kahar

Reputation: 1076

resendOtp = () => {
this.setState({
  isButtonDisabled: true,
});

this.setTimeout( () => {
   isButtonDisabled = false
},30000) //this will enable button after 30 seconds you can change time here.

this.interval = setInterval(
  () => { return this.setState((prevState) => {
    return { timer: prevState.timer - 1 }; }); },
  1000
);

this.requestOtp();

hope this works for you.

Upvotes: 2

Idan
Idan

Reputation: 4023

In onSendAndPlayTimer function you send what you need and play the timer

<TouchableOpacity
   disabled={this.state.timer != 0}
   onPress={this.onSendAndPlayTimer}>
      <Text>{'Send!'}</Text>
</TouchableOpacity>

Upvotes: 0

Related Questions