A composable for API calls helps you fetch data easily and reuse the logic in many parts of your Vue app.
0
0
Composable for API calls (useFetch pattern) in Vue
Introduction
When you want to get data from a server and show it in your app.
When you need to handle loading and error states while fetching data.
When you want to reuse the same data fetching logic in different components.
When you want to keep your components clean by moving API calls outside.
When you want to reactively update your UI based on the fetched data.
Syntax
Vue
import { ref } from 'vue'; export function useFetch(url) { const data = ref(null); const error = ref(null); const loading = ref(false); async function fetchData() { loading.value = true; error.value = null; try { const response = await fetch(url); if (!response.ok) throw new Error('Network error'); data.value = await response.json(); } catch (err) { error.value = err.message; } finally { loading.value = false; } } fetchData(); return { data, error, loading, fetchData }; }
The composable returns reactive references for data, error, and loading states.
You call the fetchData function to refresh the data anytime.
Examples
Basic usage: fetch data from a URL and get reactive states.
Vue
const { data, error, loading } = useFetch('https://api.example.com/items');
You can manually reload data by calling fetchData again.
Vue
const { data, error, loading, fetchData } = useFetch('https://api.example.com/users'); // Later in code, call fetchData() to reload
You can watch the data to react when it changes.
Vue
import { watch } from 'vue'; const { data, error, loading } = useFetch('https://api.example.com/posts'); watch(data, (newData) => { console.log('Data changed:', newData); });
Sample Program
This Vue component uses the useFetch composable to load posts from an API. It shows loading and error messages and lists post titles. The reload button lets users fetch the data again.
Vue
<template> <section aria-live="polite"> <h2>Posts</h2> <button @click="fetchData" aria-label="Reload posts">Reload</button> <p v-if="loading">Loading posts...</p> <p v-if="error" role="alert">Error: {{ error }}</p> <ul v-if="data"> <li v-for="post in data" :key="post.id">{{ post.title }}</li> </ul> </section> </template> <script setup> import { useFetch } from './useFetch'; const { data, error, loading, fetchData } = useFetch('https://jsonplaceholder.typicode.com/posts'); </script>
OutputSuccess
Important Notes
Always handle loading and error states to improve user experience.
Use aria-live and role="alert" for accessibility when showing dynamic messages.
Composable functions keep your code clean and easy to maintain.
Summary
A composable for API calls helps fetch and manage data reactively.
It returns data, loading, and error states you can use in your components.
You can reuse the same logic across your app by importing the composable.