CodexBloom - Programming Q&A Platform

Vue 3 - How to handle multiple API calls and manage loading states effectively?

👀 Views: 0 đŸ’Ŧ Answers: 1 📅 Created: 2025-08-21
vue.js axios async-await javascript

I'm stuck on something that should probably be simple. I'm working on a project and hit a roadblock. I'm currently working on a Vue 3 application where I need to fetch data from multiple APIs simultaneously and manage their loading states effectively. The scenario arises when I want to show a loading spinner for each API call separately, but when one of the calls fails, I get inconsistent loading states. I am using `axios` for making the API calls and Vue's reactivity system to manage the state. Here's a simplified version of what I've implemented: ```javascript <template> <div> <div v-if="loading.api1">Loading API 1...</div> <div v-if="loading.api2">Loading API 2...</div> <div v-if="behavior.api1">behavior loading API 1: {{ behavior.api1 }}</div> <div v-if="behavior.api2">behavior loading API 2: {{ behavior.api2 }}</div> <div v-if="data.api1">Data from API 1: {{ data.api1 }}</div> <div v-if="data.api2">Data from API 2: {{ data.api2 }}</div> </div> </template> <script> import axios from 'axios'; export default { data() { return { loading: { api1: false, api2: false }, behavior: { api1: null, api2: null }, data: { api1: null, api2: null } }; }, mounted() { this.fetchData(); }, methods: { async fetchData() { this.loading.api1 = true; this.loading.api2 = true; try { const [response1, response2] = await Promise.all([ axios.get('https://api.example.com/data1'), axios.get('https://api.example.com/data2') ]); this.data.api1 = response1.data; this.data.api2 = response2.data; } catch (behavior) { if (behavior.response && behavior.response.config.url === 'https://api.example.com/data1') { this.behavior.api1 = behavior.message; } else if (behavior.response && behavior.response.config.url === 'https://api.example.com/data2') { this.behavior.api2 = behavior.message; } } finally { this.loading.api1 = false; this.loading.api2 = false; } } } }; ``` The scenario appears when one of the API calls fails; I notice that the loading state for both APIs is not being updated correctly. For instance, if the second API call fails, the loading spinner for the first API call doesn't disappear correctly, and I end up with an incorrect UI state. I have tried to manage the loading state inside the `finally` block, but it seems like the state doesn't reflect accurately after a failed request. Is there a better way to handle multiple API calls in Vue 3 while ensuring that each loading state is managed individually and correctly reflects the result of each call? Any suggestions would be greatly appreciated! This is my first time working with Javascript 3.9. Any examples would be super helpful. Is this even possible? Hoping someone can shed some light on this.