Fetching data with useFetch
A component that fetches in onMounted shows an empty first paint: the server
renders nothing, and the data arrives only after the browser runs the code. Nuxt
gives you composables that fetch during server rendering too.
useFetch takes a URL and returns reactive state:
<script setup>
const { data, pending, error, refresh } = await useFetch('/api/posts');
</script>
data holds the response, pending is a loading flag, error holds a failure,
and refresh re-runs the request. Because the call is awaited in <script setup>, the server waits for it and renders the finished page.
useAsyncData is the same idea for any async function, not only a URL:
<script setup>
const { data } = await useAsyncData('posts', () => $fetch('/api/posts'));
</script>
The first argument is a unique key that identifies the request.
Both composables run on the server once and pass the result to the client in the
page payload. The client reuses that payload instead of fetching again, so the
same request is not made twice during hydration. For an imperative call outside
a component — an event handler, say — use $fetch directly.
You are about to answer a short quiz on fetching data in Nuxt.