What is useFetch Composable in Vue: Simple Explanation and Example
useFetch composable in Vue is a reusable function that helps you fetch data from an API easily inside your components. It manages loading, error, and response states automatically, making data fetching simple and reactive.How It Works
The useFetch composable works like a helper that wraps around the process of getting data from the internet. Imagine you want to order food from a restaurant: instead of calling the restaurant yourself, you use a delivery app that handles the order, tracks the delivery, and tells you if something goes wrong. Similarly, useFetch handles sending the request, waiting for the response, and reporting if there is an error.
It returns reactive variables for the data, loading state, and any errors. This means your Vue component can automatically update the screen when the data arrives or if an error happens, without extra code. It simplifies the common task of fetching data and keeps your component code clean and easy to read.
Example
This example shows how to use useFetch to get a list of users from a fake API and display them. It shows loading text while waiting and an error message if something goes wrong.
import { useFetch } from '@vueuse/core'; export default { setup() { const { data, error, isFetching } = useFetch('https://jsonplaceholder.typicode.com/users').json(); return { data, error, isFetching }; } };
When to Use
Use useFetch whenever you need to get data from an API in a Vue component and want to keep your code simple and reactive. It is great for loading lists, details, or any remote data that changes over time.
For example, use it to fetch blog posts, user profiles, or weather data. It saves you from writing repetitive code for loading states and error handling, letting you focus on showing the data.
Key Points
- Reactive: Automatically updates your UI when data changes.
- Simple API: Returns data, loading, and error states.
- Reusable: Use it in any component to fetch data.
- Error Handling: Built-in support for catching fetch errors.
- Integration: Works well with Vue's Composition API.