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.
Practice
useFetch and useAsyncData in Nuxt?Solution
Step 1: Understand
useFetchbehavioruseFetchfetches data from a URL quickly but does not require a key for caching.Step 2: Understand
useAsyncDatabehavioruseAsyncDataneeds a unique key to cache the fetched data, allowing more control over data reuse.Final Answer:
useAsyncDatarequires a unique key for caching,useFetchdoes not. -> Option BQuick Check:
Key caching difference = D [OK]
- Thinking useFetch caches data with keys
- Confusing client/server usage of both
- Assuming useAsyncData auto-refreshes data
useAsyncData in a Nuxt component?Solution
Step 1: Check the required parameters for
The first parameter is a unique key string, the second is a function returning a promise.useAsyncDataStep 2: Validate each option's syntax
const { data } = useAsyncData('posts', () => $fetch('/api/posts')) correctly uses a key 'posts' and a fetch function with $fetch. Others miss the key or use wrong order.Final Answer:
const { data } = useAsyncData('posts', () => $fetch('/api/posts')) -> Option AQuick Check:
Key first, fetch function second = A [OK]
- Omitting the key parameter
- Swapping parameters order
- Using native fetch instead of $fetch
const { data, pending } = useFetch('/api/user')
return { data, pending }What will
pending be initially when the component loads?Solution
Step 1: Understand
useFetchloading statependingis a reactive boolean indicating if the fetch is still in progress.Step 2: Initial value of
When the component loads and fetch starts,pendingpendingistrueuntil data arrives.Final Answer:
true -> Option CQuick Check:
Loading state pending = true [OK]
- Assuming pending is false initially
- Confusing pending with data presence
- Expecting pending to be null or undefined
const { data } = useAsyncData(() => $fetch('/api/items'))But the data never loads. What is the likely problem?
Solution
Step 1: Check
useAsyncDataparametersuseAsyncDatarequires a unique key string as the first argument for caching.Step 2: Identify missing key issue
Omitting the key causes the fetch not to run properly or cache data, so data never loads.Final Answer:
Missing a unique key as the first argument touseAsyncData. -> Option DQuick Check:
Key missing in useAsyncData = B [OK]
- Skipping the key argument
- Confusing $fetch with fetch as cause
- Expecting useAsyncData to be awaited
useAsyncData. You want posts to refresh every time the user ID changes. Which approach correctly achieves this?Solution
Step 1: Understand caching with keys in
Keys uniquely identify cached data. Changing the key triggers a new fetch.useAsyncDataStep 2: Use dynamic key with user ID
IncludinguserIdin the key string ensures posts refetch whenuserIdchanges.Step 3: Evaluate other options
Fixed keys won't refresh;useFetchdoesn't auto-refresh on param change; manual watch is more complex.Final Answer:
UseuseAsyncDatawith a key including the user ID, e.g.,useAsyncData(`posts-${userId}`, () => $fetch(`/api/posts?user=${userId}`)). -> Option AQuick Check:
Dynamic key triggers refetch = C [OK]
- Using fixed keys expecting auto-refresh
- Assuming useFetch auto-refreshes on param change
- Skipping key causes no caching or refetch
Ready to prove it?
Pass the test and this pattern moves unknown
