What are composite API calls in Vue 3, and how do you implement them efficiently?

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

  1. Define API Call Functions: Use axios or the Fetch API to create modular functions for your API requests.
  2. Leverage the Composition API: Utilize the setup function to manage state and API logic.
  3. Combine API Calls: Use utilities like Promise.all for parallel calls or .then() chains for sequential ones.
  4. 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.

Leave a comment

Your email address will not be published. Required fields are marked *