docs: advice on async setup() with multiple awaits (#1517)

This commit is contained in:
Daniel Roe 2021-10-27 13:46:52 +01:00 committed by GitHub
parent c6acee7fd4
commit 357bb7f271
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -82,7 +82,9 @@ const { data } = await useFetch('/api/count')
The data returned by `useAsyncData` will be stored inside the page payload. This means that every key returned that is not used in your component will be added to the payload. The data returned by `useAsyncData` will be stored inside the page payload. This means 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.** ::alert{icon=👉}
**We strongly recommend you only select the keys that you will use in your component.**
::
Imagine that `/api/mountains/everest` returns the following object: Imagine that `/api/mountains/everest` returns the following object:
@ -112,3 +114,33 @@ const { data: mountain } = await useFetch('/api/mountains/everest', { pick: ['ti
<p>{{ mountain.description }}</p> <p>{{ mountain.description }}</p>
</template> </template>
``` ```
### Using async setup
If you are using `async setup()`, the current component instance will be lost after the first `await`. (This is a Vue 3 limitation.) If you want to use multiple async operations, such as multiple calls to `useFetch`, you will need to use `<script setup>` or await them together at the end of setup.
::alert{icon=👉}
Using `<script setup>` is recommended, as it removes the limitation of using top-level await. [Read more](https://v3.vuejs.org/api/sfc-script-setup.html#top-level-await)
::
```vue
<script>
export default defineComponent({
async setup() {
const [{ data: organization }, { data: repos }] = await Promise.all([
useFetch(`https://api.github.com/orgs/nuxtjs`),
useFetch(`https://api.github.com/orgs/nuxtjs/repos`)
])
return {
organization,
repos
}
}
})
<template>
<h1>{{ mountain.title }}</h1>
<p>{{ mountain.description }}</p>
</template>
```