Understanding useFetch in Nuxt.js
Nuxt.js provides the useFetch composable function for efficient API data retrieval in server-rendered applications. This high-level wrapper combines useAsyncData and $fetch functionality, automatically generating keys, offering URL type hints, and inferring API response types.
Fetching Product Data
Retrieve product information from an API endpoint:
<template>
<div>
<div v-if="loading">Loading...</div>
<div v-else-if="fetchError">{{ fetchError }}</div>
<div v-else>
<ul>
<li v-for="item in products" :key="item.id">
{{ item.name }}
</li>
</ul>
</div>
</div>
</template>
<script>
export default {
setup() {
const { data: products, loading, fetchError, reload } = useFetch('https://api.store.com/items');
return { products, loading, fetchError, reload };
}
};
</script>
Handling Dynamic Parameters
Pass dynamic values to API endpoints:
<script>
export default {
setup() {
const category = ref('electronics');
const { data: products } = useFetch('https://api.store.com/items', {
query: { category, sort: 'price' }
});
return { products };
}
};
</script>
Implementing Request Interceptors
Customize request and response handling:
<script>
export default {
setup() {
const { data: user } = useFetch('/api/auth/profile', {
onRequest({ options }) {
options.headers.Authorization = `Bearer ${localStorage.getItem('authToken')}`;
},
onResponseError({ response }) {
if (response.status === 401) {
alert('Authentication required');
}
}
});
return { user };
}
};
</script>
useFetch Paramteers
The function accepts a URL string and options object:
- URL: API endpoint (absolute or relative path)
- Options:
method: HTTP method (GET, POST, etc.)query: URL query parametersbody: Request payloadheaders: Custom HTTP headersbaseURL: Base API URL
async function fetchInventory() {
const { data } = await useFetch('/stock', {
method: 'GET',
query: { warehouse: 'main' },
headers: { 'Accept': 'application/json' }
});
console.log(data.value);
}
useAsyncData Configuration
Advanced options for asynchronous data loading:
- key: Unique request identifier
- server: Fetch on server (default: true)
- lazy: Non-blocking data loading
- immediate: Execute on component initialization
- transform: Response processing function
- watch: Reactive source monitoring
const { data: stats } = useAsyncData('analytics', () => {
return $fetch('/api/analytics');
}, {
transform: (raw) => raw.metrics,
server: true
});
Return Values
Both functions return similar properties:
- data: Response payload
- pending: Loading state indicator
- refresh: Data reload function
- error: Request error informtaion
- status: Current request state