Skip to content Skip to sidebar Skip to footer

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 setTime

Solution 1:

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.

Solution 2:

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();
    awaitsetdata();

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

Post a Comment for "How Do I Add A Delay On A Button Click In React?"