Nuxt/docs/content/3.docs/1.usage/4.data-fetching.md
Sébastien Chopin 18cf0ba865
chore(docs): improvements (#655)
Co-authored-by: Sylvain Marroufin <marroufin.sylvain@gmail.com>
Co-authored-by: Pooya Parsa <pyapar@gmail.com>
2021-10-11 14:57:54 +02:00

2.3 KiB
Raw Blame History

Data Fetching

Nuxt provides useAsyncData to handle data fetching within you application.

useAsyncData

Within your pages and components you can use useAsyncData to get access to data that resolves asynchronously.

Usage

useAsyncData(key: string, fn: () => Object, options?: { defer: boolean, server: boolean })
  • key: a unique key to ensure that data fetching can be properly de-duplicated across requests
  • fn an asynchronous function that must return an object.
  • options:
    • defer: whether to load the route before resolving the async function (defaults to false)
    • server: whether the fetch the data on server-side (defaults to true)

Under the hood, defer: false uses <Suspense> to block the loading of the route before the data has been fetched. Consider using defer: true and implementing a loading state instead for a snappier user experience.

Example

<script setup>
const { data } = await useAsyncData('time', () => $fetch('/api/count'))
</script>

<template>
  Page visits: {{ data.count }}
</template>

Best practices

As seen in Concepts > Data fetching, the data returned by useAsyncData will be stored inside the page payload. This mean that every key returned that is not used in your component will be added to the payload.

We strongly recommend to only select the keys that you will use in your component.

Imagine that /api/mountains/everest returns the following object:

{
  "title": "Mount Everest",
  "description": "Mount Everest is Earth's highest mountain above sea level, located in the Mahalangur Himal sub-range of the Himalayas. The ChinaNepal border runs across its summit point",
  "height": "8,848 m",
  "countries": [
    "China",
    "Nepal"
  ],
  "continent": "Asia",
  "image": "https://upload.wikimedia.org/wikipedia/commons/thumb/f/f6/Everest_kalapatthar.jpg/600px-Everest_kalapatthar.jpg"
}

If you plan to only use title and description in your component, you can select the keys by chaining the result of $fetch:

<script setup>
const { data: mountain } = await useAsyncData('everest', () =>
  $fetch('/api/mountains/everest').then(({ title, description }) => ({ title, description }))
)
</script>

<template>
  <h1>{{ mountain.title }}</h1>
  <p>{{ mountain.description }}</p>
</template>