0
0
Vueframework~5 mins

Nuxt data fetching (useFetch, useAsyncData) in Vue

Choose your learning style9 modes available
Introduction

We use useFetch and useAsyncData in Nuxt to get data from servers easily. They help show data on pages while keeping things fast and smooth.

When you want to load data from an API to show on a page.
When you need to get data before the page appears to the user.
When you want to fetch data that updates automatically when the page changes.
When you want to handle loading and error states simply.
When you want to share fetched data between server and client without extra work.
Syntax
Vue
const { data, pending, error } = useFetch(url, options)

const { data, pending, error } = useAsyncData(key, fetcherFunction, options)

useFetch is a shortcut to fetch data from a URL directly.

useAsyncData lets you use any async function to get data, with a unique key to cache it.

Examples
Fetches user data from the API URL directly.
Vue
const { data, pending, error } = useFetch('https://api.example.com/users')
Fetches user data using a function and caches it with the key 'users'.
Vue
const { data, pending, error } = useAsyncData('users', () => $fetch('https://api.example.com/users'))
Fetches posts with a POST request instead of GET.
Vue
const { data, pending, error } = useFetch('https://api.example.com/posts', { method: 'POST' })
Sample Program

This component fetches a list of users from a public API. It shows a loading message while waiting, an error message if something goes wrong, and the user list when data is ready. It uses semantic HTML and ARIA for accessibility.

Vue
<script setup>
const { data: users, pending, error } = useFetch('https://jsonplaceholder.typicode.com/users')
</script>

<template>
  <section aria-live="polite">
    <h1>Users List</h1>
    <div v-if="pending">Loading users...</div>
    <div v-else-if="error">Error loading users.</div>
    <ul v-else>
      <li v-for="user in users" :key="user.id">
        <strong>{{ user.name }}</strong> - {{ user.email }}
      </li>
    </ul>
  </section>
</template>
OutputSuccess
Important Notes

Both useFetch and useAsyncData run on server and client automatically.

Use the pending property to show loading states for better user experience.

Always handle error to show friendly messages if data fails to load.

Summary

useFetch is a quick way to get data from a URL.

useAsyncData is more flexible and uses a key to cache data.

Both help load data before showing the page, improving speed and user experience.