JAVASCRIPT

Building a Reusable Vue 3 Composable for Fetching Data

Discover how to create custom composables in Vue 3 to encapsulate and reuse reactive logic, like data fetching, across multiple components effectively.

// useFetch.js (a composable file)
import { ref, onMounted, toRefs } from 'vue';

export function useFetch(url) {
  const data = ref(null);
  const error = ref(null);
  const loading = ref(true);

  const fetchData = async () => {
    loading.value = true;
    try {
      const res = await fetch(url);
      if (!res.ok) throw new Error(`HTTP error! status: ${res.status}`);
      data.value = await res.json();
    } catch (e) {
      error.value = e;
    } finally {
      loading.value = false;
    }
  };

  onMounted(() => {
    fetchData();
  });

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

// MyComponent.vue
<template>
  <div>
    <div v-if="loading">Loading data...</div>
    <div v-else-if="error">Error: {{ error.message }}</div>
    <div v-else>
      <h2>Fetched Data:</h2>
      <pre>{{ data }}</pre>
      <button @click="fetchData">Refresh Data</button>
    </div>
  </div>
</template>

<script setup>
import { useFetch } from './useFetch'; // Adjust path as needed

const { data, error, loading, fetchData } = useFetch('https://jsonplaceholder.typicode.com/todos/1');
</script>
How it works: This snippet illustrates how to create a reusable 'composable' in Vue 3, which is a function that leverages the Composition API to encapsulate stateful logic. The `useFetch` composable abstracts data fetching, providing reactive `data`, `error`, and `loading` states. By moving this logic into a composable, it can be easily reused across multiple components, promoting code organization, maintainability, and reusability without duplicating code.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs