Data Fetching

1/3/2025

Data Fetching in Nuxt

Nuxt provides powerful composables for fetching data from APIs.

useFetch

The useFetch composable is the most straightforward way to fetch data:

vue
<script setup>
const { data, pending, error } = await useFetch('/api/users')
</script>

<template>
  <div v-if="pending">Loading...</div>
  <div v-else-if="error">Error: {{ error.message }}</div>
  <ul v-else>
    <li v-for="user in data" :key="user.id">{{ user.name }}</li>
  </ul>
</template>

useAsyncData

For more control over data fetching:

vue
<script setup>
const { data } = await useAsyncData('users', () => {
  return $fetch('/api/users')
})
</script>

Lazy Loading

Use useLazyFetch for non-blocking data fetching:

vue
<script setup>
const { data, pending } = useLazyFetch('/api/users')
</script>

Refresh Data

vue
<script setup>
const { data, refresh } = await useFetch('/api/users')

async function updateData() {
  await refresh()
}
</script>