search

Home  >  Q&A  >  body text

Waiting for Requests and User Input: A Guide to Patient Expectations

Suppose I make an asynchronous request when the component loads. The component also has a submit button that the user can press to trigger a function that depends on the result of the original request. How can I delay the execution of a triggered function until the async request completes?

If this doesn't make sense, let me give you an example. MyComponent Makes an asynchronous request getRandomColor() on mounted. The template of MyComponent has <button @click="handleClick">. handleClick Call some functions saveColor(). How do I ensure that saveColor() is not called before the async getRandomColor() completes?

I'm currently using Vue.js, but I think this question applies to all javascript.

P粉368878176P粉368878176270 days ago344

reply all(1)I'll reply

  • P粉329425839

    P粉3294258392024-02-27 00:34:47

    You can achieve this by adding the :disabled attribute to the button element. The value of :disabled will be based on the response. That is, if there is a response, enable it, otherwise disable it.

    Working Demonstration:

    const app = Vue.createApp({
      el: '#app',
      data() {
        return {
            buttonText: 'Call Me!',
          apiResponse: [],
          isDisabled: false
        }
      },
      methods: {
        saveColor() {
            console.log('saveColor method call');
        }
      },
      mounted() {
        axios.get("https://jsonplaceholder.typicode.com/users").then(response => {
          this.apiResponse = response.data; // Here we are getting proper response. hence, button is getting enabled.
        }).catch((error) => {
            console.warn('API error');
            });
      }
    })
    app.mount('#app')
    
    
    
    

    reply
    0
  • Cancelreply