JAVASCRIPT
Create a Reusable Vue 3 Composable for Async Data Fetching
Learn to build a custom Vue 3 composable to encapsulate and reuse asynchronous data fetching logic, complete with loading and error states for better UX.
// composables/useFetch.js
import { ref, onMounted, toValue } from 'vue';
export function useFetch(url) {
const data = ref(null);
const error = ref(null);
const loading = ref(true);
async function doFetch() {
loading.value = true;
error.value = null;
data.value = null;
try {
const response = await fetch(toValue(url));
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
data.value = await response.json();
} catch (e) {
error.value = e;
} finally {
loading.value = false;
}
}
onMounted(doFetch);
return { data, error, loading, refetch: doFetch };
}
// Usage in a Vue component (e.g., App.vue)
// <template>
// <div>
// <div v-if="loading">Loading posts...</div>
// <div v-else-if="error">Error: {{ error.message }}</div>
// <ul v-else>
// <li v-for="post in data" :key="post.id">{{ post.title }}</li>
// </ul>
// <button @click="refetch">Refetch Posts</button>
// </div>
// </template>
// <script setup>
// import { useFetch } from './composables/useFetch';
// import { ref } from 'vue';
// const postId = ref(1);
// const url = `https://jsonplaceholder.typicode.com/posts/${postId.value}`;
// // Or, to make the URL reactive:
// // const url = computed(() => `https://jsonplaceholder.typicode.com/posts/${postId.value}`);
// const { data, error, loading, refetch } = useFetch(url);
// </script>
How it works: This snippet demonstrates how to create a Vue 3 composable function, `useFetch`, for handling asynchronous data requests. It encapsulates reactivity for `data`, `error`, and `loading` states. The `doFetch` function performs the actual HTTP request. `onMounted` ensures the data is fetched when the component using the composable is mounted. The composable returns reactive references and a `refetch` method, making it highly reusable across different components to manage data fetching logic consistently, reducing boilerplate and improving maintainability. The `toValue` utility ensures that the URL can be either a static string or a reactive reference.