Vue3 Fundamentals · Nuxt & Server-Side Rendering

Fetching data with useFetch

data fetching with useFetch and useAsyncData

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.

  1. `useFetch` returns reactive `data`, `pending`, and `error` state.
  2. Awaiting `useFetch` in `<script setup>` lets the ___ wait for the data before rendering.
  3. `useAsyncData` can wrap any async function, not only a URL.
  4. `useAsyncData`'s first argument is a unique ___ that identifies the request.
  5. The client fetches the same data again during hydration instead of reusing the server payload.
  6. For an imperative call outside a component, use ___ directly.