Prevent Clicking Again When Submitting Form in React

I have a form in my React app and i wanted to disable or not be able to click the Pay button once i have submitted it. The problem is, that it is not submitting through API but through a <form>.

Form

<form ref={formEl} action="https://sample.aspx" method="POST">
  <input name="order" id="order" value={base64String} readOnly type="hidden" />
</form>

Button

<Button onClick={() => onPay(order.id)}>Pay</Button>;

Pay Function

const onPay = (id) => {
  formEl.current && formEl.current.submit();
};

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

If you want to implement this functionality, you should use form event onSubmit. Use any HTTP client like fetch or axios to call API. You can use a state value to track submission status.

Form

    <form ref={formEl} action="https://sample.aspx" method="POST" onSubmit={onSubmit}>
      <input name="order" id="order" value={base64String} readOnly type="hidden" />
    </form>

Button

    <Button onClick={() => onPay(order.id)}>Pay</Button>;

State

const [submitting, setSubmitting] = useState(false)

Pay Function

const onPay = (id) => {
  if (submitting) return;
  formEl.current && formEl.current.submit();
};

Submit Function

const onSubmit = async (event) => {
  event.preventDefault();
  setSubmitting(true);
  await fetch('https://sample.aspx');
  setSubmitting(false);
}

Method 2

You can use useState to keep track of when the button is clicked:

const [paid, setPaid] = useState(false)

Then set the button’s enabled state based on the above. You can toggle the boolean within your onPay function.

Method 3

  1. You can use boolean value to disable and enable it within useState.
     const [_boolValue, setBoolValue] = useState(true);
    
     <Button onClick={() => {
     setBoolValue(!_boolValue)
     onPay(order.id)
     }}>Pay</Button>;
  2. then it will work only _boolValue == true
     const onPay = (id) => {
       _boolValue && formEl.current && formEl.current.submit();
     };


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x