useAxiosFetch Documentation
useAxiosFetch is an HTTP request utility based on Axios, designed for Nuxt 3 applications with support for server-side rendering and client-side requests. It provides advanced features such as request caching and unified error handling.
Features
- ✅ Fully typed API
- ✅ Server-side rendering support (SSR)
- ✅ Request caching mechanism (based on Nuxt useAsyncData)
- ✅ Unified error handling (automatic error notifications)
- ✅ Debounced error notifications (no duplicate messages within 3 seconds)
- ✅ Automatic authentication handling (401 auto-redirect to login)
Installation
This component is already integrated into the project, no additional installation required.
Basic Usage
Import
import {useAxiosFetch} from "~/composables/useAxiosFetch"GET Request
const {data, error} = await useAxiosFetch("/api/users", {
method: "GET",
params: {page: 1},
})POST Request
const {data, error} = await useAxiosFetch("/api/users", {
method: "POST",
data: {
name: "John",
email: "john@example.com",
},
})PUT Request
const {data, error} = await useAxiosFetch("/api/users/1", {
method: "PUT",
data: {
name: "Updated Name",
},
})DELETE Request
const {data, error} = await useAxiosFetch("/api/users/1", {
method: "DELETE",
})Configuration Options
interface RequestOptions {
// Axios configuration
data?: any // Request body data
params?: Record<string, any> // URL parameters
method?: string // HTTP method
headers?: Record<string, string> // Request headers
baseURL?: string // Base URL
timeout?: number // Timeout (milliseconds)
// Nuxt useAsyncData configuration
server?: boolean // Execute on server (default: true)
lazy?: boolean // Lazy execution (default: false)
immediate?: boolean // Immediate execution (default: true)
deep?: boolean // Deep reactivity (default: false)
watch?: any[] | false // Watch dependencies
transform?: (input: any) => any // Transform function
pick?: string[] // Pick fields
default?: () => any // Default value function
}Response Type
interface RequestResponse<T> {
data: T | null // Response data
error: any // Error object
}Error Handling
useAxiosFetch automatically handles errors and displays error notifications:
- 401 Unauthorized: Automatically redirects to login page
- 404 Not Found: Displays "Resource Not Found" error
- Other errors: Displays "Server Error" error
Error notifications have a 3-second debounce mechanism, meaning the same error message will only be displayed once within a short time.
Request Caching
useAxiosFetch uses Nuxt's useAsyncData for request caching. The cache key is composed of:
- URL
- HTTP method
- Request parameters
- Request body data
This ensures that identical requests are read from cache, improving performance.
Best Practices
1. Use Type Parameters
interface User {
id: number
name: string
email: string
}
const {data} = await useAxiosFetch<User>("/api/users/1")
// data type is User | null2. Use in Components
<template>
<div v-if="!data">Loading...</div>
<div v-else-if="error">Error: {{ error.message }}</div>
<div v-else>{{ data }}</div>
</template>
<script setup>
const {data, error} = await useAxiosFetch("/api/users")
</script>3. Combine Multiple Requests
const [users, posts] = await Promise.all([
useAxiosFetch("/api/users", {method: "GET"}),
useAxiosFetch("/api/posts", {method: "GET"})
])
// Access data
const userData = users.data
const postsData = posts.data4. Dynamic Requests
<script setup>
import {ref} from "vue"
import {useAxiosFetch} from "~/composables/useAxiosFetch"
const users = ref(null)
async function fetchUsers(page: number = 1) {
const {data} = await useAxiosFetch(`/api/users?page=${page}`, {
method: "GET",
})
users.value = data
}
// Initial load
fetchUsers()
</script>Notes
- Server-side rendering (SSR) support: By default, requests are executed on the server
- 401 errors automatically redirect to the login page
- Error notifications have a 3-second debounce mechanism
- Cache is based on the combination of URL, method, parameters, and data
- It is recommended to use type parameters for better type hints
Technical Details
Unified Response Format
API responses should follow the following format:
{
"code": 0,
"message": "success",
"data": {}
}code: 0indicates successcode !== 0indicates a business error
Global Configuration
The following configuration is globally set in useAxiosFetch:
{
baseURL: process.env.HOST, // Read from environment variable
timeout: 10000, // 10 second timeout
headers: {
'Content-Type': 'application/json',
},
}