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.
You can achieve this by adding the
:disabledattribute to the button element. The value of:disabledwill 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')