Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Optimizing Data Fetching in Nuxt.js with useFetch

Tech Nov 2 1

Nuxt.js provides powerful tools for server-side rendered applications, with useFetch being a key composable for efficient API data retrieval. This function combines useAsyncData and $fetch, automatically generating keys, providing URL type hints, and inferring response types.

Basic Implementation

Fetching data from an API endpoint:

<template>
  <div>
    <div v-if="loading">Loading content...</div>
    <div v-else-if="fetchError">{{ fetchError }}</div>
    <div v-else>
      <ul>
        <li v-for="item in responseData" :key="item.id">
          {{ item.name }}
        </li>
      </ul>
    </div>
  </div>
</template>

<script setup>
const { data: responseData, pending: loading, error: fetchError } = 
  useFetch('https://api.service.com/resources');
</script>

Dynamic Parameter Handling

Passing URL parameters:

const searchTerm = ref('');
const { data } = useFetch('/api/search', {
  query: { q: searchTerm, limit: 20 }
});

Request Interceptors

Modifying requests and responses:

const { data } = useFetch('/auth', {
  onRequest({ options }) {
    options.headers = {
      ...options.headers,
      Authorization: `Bearer ${localStorage.token}`
    };
  },
  onResponse({ response }) {
    if (response.data.accessToken) {
      localStorage.setItem('token', response.data.accessToken);
    }
  }
});

Configuration Options

Key parameters for useFetch:

  • url: API endpoint (string)
  • options: Configuration object including:
    • method: HTTP method (GET/POST/PUT/DELETE)
    • query: URL parameters
    • headers: Request headers
    • body: Request payload
    • baseURL: Root API URL

useAsyncData Integration

When using useAsyncData directly:

const { data } = useAsyncData('unique-key', async () => {
  return await $fetch('/api/data');
}, {
  lazy: true,
  server: false,
  transform: (rawData) => rawData.results
});

Related Articles

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.