Skip to content

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

typescript
import {useAxiosFetch} from "~/composables/useAxiosFetch"

GET Request

typescript
const {data, error} = await useAxiosFetch("/api/users", {
  method: "GET",
  params: {page: 1},
})

POST Request

typescript
const {data, error} = await useAxiosFetch("/api/users", {
  method: "POST",
  data: {
    name: "John",
    email: "john@example.com",
  },
})

PUT Request

typescript
const {data, error} = await useAxiosFetch("/api/users/1", {
  method: "PUT",
  data: {
    name: "Updated Name",
  },
})

DELETE Request

typescript
const {data, error} = await useAxiosFetch("/api/users/1", {
  method: "DELETE",
})

Configuration Options

typescript
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

typescript
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

typescript
interface User {
  id: number
  name: string
  email: string
}

const {data} = await useAxiosFetch<User>("/api/users/1")
// data type is User | null

2. Use in Components

vue
<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

typescript
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.data

4. Dynamic Requests

vue
<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

  1. Server-side rendering (SSR) support: By default, requests are executed on the server
  2. 401 errors automatically redirect to the login page
  3. Error notifications have a 3-second debounce mechanism
  4. Cache is based on the combination of URL, method, parameters, and data
  5. It is recommended to use type parameters for better type hints

Technical Details

Unified Response Format

API responses should follow the following format:

json
{
  "code": 0,
  "message": "success",
  "data": {}
}
  • code: 0 indicates success
  • code !== 0 indicates a business error

Global Configuration

The following configuration is globally set in useAxiosFetch:

typescript
{
  baseURL: process.env.HOST,  // Read from environment variable
  timeout: 10000,  // 10 second timeout
  headers: {
    'Content-Type': 'application/json',
  },
}