vue.js logo

Using Composition API for Reusable Logic


Step 1: Create a Composable Function

In your Vue project, create a new file for your composable. For instance, create a file named useApi.js in a composables directory. This composable will be responsible for fetching data from an API and managing its state.


          import { ref, onMounted } from 'vue';

      export function useApi(url) {
        const data = ref(null);
        const loading = ref(false);
        const error = ref(null);

        const fetchData = async () => {
          loading.value = true;
          error.value = null;
          try {
            const response = await fetch(url);
            data.value = await response.json();
            loading.value = false;
          } catch (e) {
            error.value = e;
            loading.value = false;
          }
        };

        onMounted(fetchData);

        return { data, loading, error, fetchData };
      }
      

Step 2: Use Your Composable in a Component

Now, integrate the composable into a Vue component. Create or modify a Vue component to use the useApi composable.


<template>
  <div>
    <h1>Data Fetching Example</h1>
    <div v-if="loading">Loading...</div>
    <div v-if="error">Error: {{ error.message }}</div>
    <pre v-if="data">{{ data }}</pre>
    <button @click="fetchData">Refresh Data</button>
  </div>
</template>

<script>
import { useApi } from './composables/useApi';

export default {
  setup() {
    const { data, loading, error, fetchData } = useApi('https://api.example.com/data');

    return { data, loading, error, fetchData };
  }
}
</script>

Conclusion

With these steps, you’ve created a reusable logic piece using Vue’s Composition API that manages API data fetching. This approach is highly modular, making it easy to reuse and test. Composables can be further expanded with more complex logic, dependencies, or even by using other composables within them. This pattern helps in keeping your application scalable and maintainable.