Learn Nuxt Β· 4/12

Data Fetching: Mastering Server and Client State

6 min read

Data Fetching: Mastering Server and Client State πŸ“Š

Welcome, fellow developer! Let's talk about one of the most crucial parts of any web application: getting data. In the world of Nuxt, we have some powerful tools at our disposal that make data fetching a breeze, both on the server and the client. Think of your Nuxt application as a brand new restaurant. You need a reliable way to get fresh ingredients (data) from your suppliers (APIs) to serve delightful dishes (web pages) to your customers (users). Let's learn how to be a master chef in our Nuxt kitchen!

The Power of useFetch: The Nuxt Way πŸš€

The Problem: You need to fetch data from an API and display it on a page. You want it to be fast, efficient, and work seamlessly with server-side rendering (SSR). Doing this manually would involve a lot of boilerplate code to handle loading states, errors, and making sure it doesn't re-fetch unnecessarily on the client-side.

The Solution: useFetch is your go-to helper for most data fetching needs in Nuxt. It's a simple yet powerful composable that handles the complexities for you. It's like having a dedicated kitchen porter who knows exactly which supplier to go to, when to go, and how to bring back the ingredients perfectly every time.

Under the hood, useFetch is a wrapper around another powerful Nuxt tool called useAsyncData. It's designed for the most common use case: fetching data from a URL.

How it Works:

Let's say we want to fetch a list of products for our e-commerce site.

vue
<template>
  <div>
    <h1>Products</h1>
    <div v-if="pending">
      Loading...
    </div>
    <div v-else-if="error">
      <p>Oops! Something went wrong: {{ error.message }}</p>
    </div>
    <ul v-else>
      <li v-for="product in products" :key="product.id">
        {{ product.title }}
      </li>
    </ul>
  </div>
</template>

<script setup>
const { data: products, pending, error } = await useFetch('https://fakestoreapi.com/products')
</script>

Breaking it down:

  • useFetch('https://fakestoreapi.com/products'): This single line is doing a lot of heavy lifting. It calls the API endpoint.
  • data: products: The fetched data is available in the data ref, which we are renaming to products for clarity.
  • pending: This is a boolean ref that is true while the data is being fetched and false once it's done. This is perfect for showing a loading indicator.
  • error: If something goes wrong with the request, this ref will contain the error object.

A Fun Fact: useFetch is "isomorphic," which is a fancy way of saying it runs on both the server and the client. When you first load the page, it fetches the data on the server, so the content is rendered in the initial HTML. This is great for SEO and perceived performance. Then, it seamlessly "hydrates" on the client-side without re-fetching the same data.

useAsyncData: Complex Data Fetching Scenarios 🧠

The Problem: What if your data fetching logic is more complex than just calling a single URL? Maybe you need to perform some transformations on the data, or perhaps the data source isn't a simple GET request.

The Solution: useAsyncData gives you more control. It allows you to define your own asynchronous function for fetching data. It's like being the head chef; you're not just getting ingredients, you're deciding on the recipe.

How it Works:

useAsyncData takes two main arguments: a unique key and an asynchronous function that returns the data.

vue
<template>
  <div>
    <h1>User Profile</h1>
    <div v-if="pending">
      Fetching your profile...
    </div>
    <div v-else-if="error">
      <p>Could not fetch profile: {{ error.message }}</p>
    </div>
    <div v-else>
      <p>Welcome, {{ user.name }}!</p>
    </div>
  </div>
</template>

<script setup>
const { data: user, pending, error } = await useAsyncData(
  'user-profile',
  () => $fetch('https://api.yourapp.com/user/1')
)
</script>

Breaking it down:

  • 'user-profile': This is a unique key. Nuxt uses this key to ensure that the same data is not fetched multiple times across your application.
  • () => $fetch('https://api.yourapp.com/user/1'): This is our asynchronous function. Here, we're using $fetch, but you could have more complex logic inside this function.

When to use useAsyncData over useFetch?

  • When you need to perform complex logic before or after fetching.
  • When you are fetching from a source that isn't a direct URL (e.g., a database, a local file).
  • When you need more control over caching with the unique key.

Handling Loading and Error States in UI ⏳❌

The Problem: A user clicks a button, and... nothing happens for a few seconds. Did the click register? Is the app broken? This is a bad user experience. We need to give users feedback about what's happening.

The Solution: Both useFetch and useAsyncData return pending and error refs that make it incredibly easy to manage these states in your UI.

Let's imagine our restaurant again. If a customer orders a dish, you'd tell them, "Your order is being prepared" (loading state). If you run out of an ingredient, you'd inform them, "Apologies, we can't make that right now" (error state). You wouldn't just leave them waiting in silence!

A Practical Example:

vue
<template>
  <div>
    <h2>Latest News</h2>
    <div v-if="pending" class="loading-spinner">
      <p>Fetching the freshest headlines... πŸ“°</p>
    </div>
    <div v-else-if="error" class="error-message">
      <p>Oh no! We couldn't reach the newsroom. Please try again later.</p>
      <button @click="refresh">Try Again</button>
    </div>
    <ul v-else>
      <li v-for="article in news" :key="article.id">{{ article.title }}</li>
    </ul>
  </div>
</template>

<script setup>
const { data: news, pending, error, refresh } = await useFetch('/api/news')
</script>

In this example, we're providing a much better user experience by:

  • Showing a loading message while pending is true.
  • Displaying a user-friendly error message if error has a value.
  • We've also destructured the refresh function, which allows the user to retry the data fetching operation.

Industry Standard: Always provide feedback for asynchronous operations. A simple loading spinner and a clear error message can significantly improve how users perceive your application.

$fetch: Making Client-Side Network Requests πŸ’»

The Problem: You've already loaded a page, and now the user performs an action that requires fetching new data without a full page reload. For example, submitting a form or fetching more items in an infinite scroll. useFetch and useAsyncData are primarily for fetching data needed to render a route.

The Solution: $fetch is a utility provided by Nuxt for making network requests. It's great for client-side interactions. Think of it as your waiter who can quickly go back to the kitchen to fetch an extra side of fries (data) for a customer who is already dining.

How it Works:

$fetch is automatically available in your components. You can use it just like you would use the fetch API, but with some nice enhancements.

vue
<template>
  <div>
    <button @click="sendMessage" :disabled="isSending">
      {{ isSending ? 'Sending...' : 'Send Message' }}
    </button>
    <p v-if="successMessage">{{ successMessage }}</p>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const isSending = ref(false)
const successMessage = ref('')

async function sendMessage() {
  isSending.value = true
  successMessage.value = ''
  try {
    const response = await $fetch('/api/contact', {
      method: 'POST',
      body: { message: 'Hello, Nuxt!' }
    })
    successMessage.value = response.message
  } catch (error) {
    alert('Error sending message: ' + error.data.message)
  } finally {
    isSending.value = false
  }
}
</script>

When to use $fetch?

  • For handling user interactions like form submissions.
  • For any data fetching that is not directly tied to the initial rendering of a page component.
  • When you need to make API calls in response to client-side events.

Interesting Tidbit: $fetch is built on top of a library called ofetch, which provides features like automatic JSON parsing and error handling, making it more convenient than the standard fetch API.


Further Reading πŸ“š

To dive deeper into these concepts, the official Nuxt documentation is your best friend. It's always up-to-date and packed with more examples and advanced use cases.

Challenge

You are building a product details page in a Nuxt 3 application. Your task is to fetch data for a single product from the API endpoint /api/products/1 and display it, while also handling loading and error states.

Requirements:

  1. In the <script setup> section, use the useFetch composable to make a GET request to /api/products/1.
  2. Destructure the data, pending, error, and refresh properties from the useFetch return value. Assume the data ref will hold an object with name and description properties upon a successful fetch.
  3. In the <template> section, implement conditional rendering to handle all three possible states of the data fetching lifecycle:
    • If the request is pending (pending is true), display a <p> tag with the text "Loading product...".
    • If an error occurs (error is truthy), display a <div> containing a <p> tag with the text "Failed to fetch product." and a <button> with the text "Retry". This button, when clicked, must trigger the refresh function to re-attempt the fetch.
    • If the data has been successfully fetched (and is not pending or in an error state), display an <h1> tag with the product's name (data.name) and a <p> tag with the product's description (data.description).

Expected result

Your component should correctly use the useFetch composable and implement conditional rendering in the template to handle the loading, error, and success states.

The <script setup> block should contain the useFetch call, destructuring its return value.

javascript
const { data, pending, error, refresh } = useFetch('/api/products/1');

The <template> should use v-if, v-else-if, and v-else directives to display the appropriate content based on the pending and error refs. The 'Retry' button in the error state must be bound to the refresh function using @click.

Here is a complete example of the expected solution:

vue
<template>
  <div>
    <div v-if="pending">
      <p>Loading product...</p>
    </div>
    <div v-else-if="error">
      <p>Failed to fetch product.</p>
      <button @click="refresh">Retry</button>
    </div>
    <div v-else>
      <h1>{{ data.name }}</h1>
      <p>{{ data.description }}</p>
    </div>
  </div>
</template>

<script setup>
const { data, pending, error, refresh } = useFetch('/api/products/1');
</script>
vue

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.