In Vue 3, composite API calls refer to the practice of combining multiple API requests into a single, orchestrated process. Instead of handling each API call separately, you coordinate them in a structured way, which simplifies your code and ensures dependencies between calls are handled correctly.
How to Implement Composite API Calls in Vue 3
- Define API Call Functions: Use
axiosor the Fetch API to create modular functions for your API requests. - Leverage the Composition API: Utilize the
setupfunction to manage state and API logic. - Combine API Calls: Use utilities like
Promise.allfor parallel calls or.then()chains for sequential ones. - Handle Errors Gracefully: Ensure robust error handling to manage individual or overall failures.
Example:
<template>
<div>
<div v-if="loading">Loading...</div>
<div v-else-if="error">Error: {{ error }}</div>
<div v-else>
<p>API 1 Data: {{ data1 }}</p>
<p>API 2 Data: {{ data2 }}</p>
</div>
</div>
</template>
<script>
import { ref, onMounted } from 'vue';
import axios from 'axios';
export default {
setup() {
const data1 = ref(null);
const data2 = ref(null);
const loading = ref(true);
const error = ref(null);
const fetchData = async () => {
loading.value = true;
try {
const [res1, res2] = await Promise.all([
axios.get('https://api.example.com/data1'),
axios.get('https://api.example.com/data2'),
]);
data1.value = res1.data;
data2.value = res2.data;
} catch (err) {
error.value = err.message;
} finally {
loading.value = false;
}
};
onMounted(fetchData);
return {
data1,
data2,
loading,
error,
};
},
};
</script>
Why Use Composite API Calls?
- Improved Performance: Fetch multiple independent data sources in parallel.
- Simplified Code: Centralize and organize API logic for better maintainability.
- Error Isolation: Handle failures for specific calls without impacting others.