1

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);
3
  • 1
    onClick={this.handleCardSubmit} try this onClick={()=>this.handleCardSubmit()} Commented Nov 22, 2019 at 5:03
  • You are not using evt.preventDefault(), you are not returning false; if your button is a submit button, it will do what submit buttons do: submit. Commented Nov 22, 2019 at 5:04
  • 2
    why cant you use setTimeout for onclick then ? onClick={()=>setTimeout(() => {this.handleCardSubmit()},500)} ..just asking ? Commented Nov 22, 2019 at 5:06

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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 });
}
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.