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.
Nuxt data fetching (useFetch, useAsyncData) in 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.
const { data, pending, error } = useFetch('https://api.example.com/users')
const { data, pending, error } = useAsyncData('users', () => $fetch('https://api.example.com/users'))
const { data, pending, error } = useFetch('https://api.example.com/posts', { method: 'POST' })
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.
<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>
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.
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.