LDB
LDB

Reputation: 611

How do I add a delay on a button click in react?

I'm attempting to delay a button click so that the library I'm using can make a quick api call for validation. I'm currently using an arrow function in react and attempting setTimeout. However it appears this is triggering a call on page load for some reason. Here's my code.

  onClick={this.handleCardSubmit}

handleCardSubmit = setTimeout(() => {
    this.setState({ showLoaderForPayment: true });
    const { collectJs } = this.state;
    collectJs.startPaymentRequest();
    this.setState({ isPaymentRequestCalled: true });
  }, 500);

Upvotes: 1

Views: 8503

Answers (2)

Pushprajsinh Chudasama
Pushprajsinh Chudasama

Reputation: 7979

You can use e.preventDefault(), and try the below code.

handleCardSubmit = (e) => {
    e.preventDefault();
    setTimeout(() => {
    this.setState({ showLoaderForPayment: true });
    const { collectJs } = this.state;
    collectJs.startPaymentRequest();
    this.setState({ isPaymentRequestCalled: true });
  }, 500);
};

Or you can use async-await.

handleCardSubmit = async (e) => {
    e.preventDefault();
    await setdata();

    setdata() {
    this.setState({ showLoaderForPayment: true });
    const { collectJs } = this.state;
    collectJs.startPaymentRequest();
    this.setState({ isPaymentRequestCalled: true });
}
};

Upvotes: 0

developerKumar
developerKumar

Reputation: 1796

Hi you need to change you function declaration and definition as follows

handleCardSubmit = ()=>{
setTimeout(() => {
    this.setState({ showLoaderForPayment: true });
    const { collectJs } = this.state;
    collectJs.startPaymentRequest();
    this.setState({ isPaymentRequestCalled: true });
  }, 500);
}

In you code snippet, you are just passing the settimeout function reference to handeCardSubmit , so there is not binding of this. In order to execute it properly, you will have to write setTimeout function inside an arrow function, then it will work as with delay of 500ms.

Upvotes: 2

Related Questions