Preventing form from submitting multiple times

Viewed 3262

I've attempted using vuejs to create a form which ultimately uses axios to do a POST request. However, the submit button does not disable during form validation. I am trying to prevent the user from submitting multiple times…

Code to reproduce:

<div>
    <form @submit.prevent="checkForm">
    <input
        type="submit"
        :disabled="submitting"
        :value="value"
    >
</div>

Where:

checkForm( e ) {
    this.submitting = true;
    this.value = 'Submitting';

    // Form Validation

    this.submitting = false;
    this.value = 'Submit';
}
1 Answers

From the comments, it sounds like you're making an asynchronous request (in axios.post()) and immediately setting this.submitting and this.value without awaiting the result of the network request, similar to this example:

checkForm( e ) {
  this.submitting = true;
  this.value = 'Submitting';

  axios.post('https://foo');

  this.submitting = false;
  this.value = 'Submit';
}

Since axios.post() is asynchronous (i.e., returns a Promise), the lines that follow are executed before the POST request even occurs. You can either move those settings into the then callback of axios.post():

checkForm( e ) {
  this.submitting = true;
  this.value = 'Submitting';

  axios.post('https://foo').then(() => {
    this.submitting = false;
    this.value = 'Submit';
  });
}

Or you can use async/await like this:

async checkForm( e ) {
  this.submitting = true;
  this.value = 'Submitting';

  await axios.post('https://foo');

  this.submitting = false;
  this.value = 'Submit';
}

demo

Related