ToddT
ToddT

Reputation: 3258

Wait for a submit event to finish before calling async function

I want to run an async function after a form has completed its submit. The form updates a shopping cart, and I need to grab the products from the cart after they've been added.

I've tried a million things and nothing seems to wait until the form has COMPLETED submitting before running my code. I don't want to use any sort of timing events.

Here is the latest couple versions of code I have. They both do the same thing and run prior to the submit being finished:

window.addEventListener(
  'submit', 
  () => vueFreshie.$options.components['fresh-credit'].options.methods.getCart(), 
  false
)

window.addEventListener("submit", async e => {
  await vueFreshie.$options.components['fresh-credit'].options.methods.getCart()
}, false)

this is the Vue method I'm calling, and I've simplified it for examples sake.

  methods: {
    async getCart() {
      let response = await axios.get(`/cart.js`)
      debugger
    }
  }

the method is called fine, its just too early and the cart has not been updated.

Upvotes: 0

Views: 1925

Answers (1)

Salvino D'sa
Salvino D'sa

Reputation: 4506

Here you go: I've used a onSubmit event handler to listen to the form submission & axios to explicitly post the data to my server. This way I have more control over the submission request and I can await for its completion before proceeding to the getCart API.

new Vue({
  el: "#app",
  data: () => {
    return {
      formData: {
        firstName: '',
        lastName: ''
      }
    }
  },
  methods: {
    async onSubmit() {
      const {data} = await axios.post('https://jsonplaceholder.typicode.com/posts', this.formData);
      console.log('response from submitted request', data);
      await this.getCart();
    },

    async getCart() {
      console.log('safe to call the get cart API now');
      const {data} = await axios.get('https://jsonplaceholder.typicode.com/posts');
      console.log('response from cart api', data);
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<div id="app">
  <form v-on:submit.prevent="onSubmit">
    <input name="firstName" v-model="formData.firstName"><br/>
    <input name="lastName" v-model="formData.lastName">
    <button type="submit">SUBMIT</button>
  </form>
</div>

Reference

Upvotes: 1

Related Questions