docs: add context for useAsyncData side effects (#30479)

This commit is contained in:
Camille Coutens 2025-01-14 15:05:29 +01:00 committed by GitHub
parent 5be18cf4b0
commit 406732ad44
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 17 additions and 1 deletions

View File

@ -202,6 +202,19 @@ const { data: discounts, status } = await useAsyncData('cart-discount', async ()
</script> </script>
``` ```
::note
`useAsyncData` is for fetching and caching data, not triggering side effects like calling Pinia actions, as this can cause unintended behavior such as repeated executions with nullish values. If you need to trigger side effects, use the [`callOnce`](/docs/api/utils/call-once) utility to do so.
```vue
<script setup lang="ts">
const offersStore = useOffersStore()
// you can't do this
await useAsyncData(() => offersStore.getOffer(route.params.slug))
</script>
```
::
::read-more{to="/docs/api/composables/use-async-data"} ::read-more{to="/docs/api/composables/use-async-data"}
Read more about `useAsyncData`. Read more about `useAsyncData`.
:: ::

View File

@ -62,7 +62,10 @@ const { data: posts } = await useAsyncData(
## Params ## Params
- `key`: a unique key to ensure that data fetching can be properly de-duplicated across requests. If you do not provide a key, then a key that is unique to the file name and line number of the instance of `useAsyncData` will be generated for you. - `key`: a unique key to ensure that data fetching can be properly de-duplicated across requests. If you do not provide a key, then a key that is unique to the file name and line number of the instance of `useAsyncData` will be generated for you.
- `handler`: an asynchronous function that must return a truthy value (for example, it should not be `undefined` or `null`) or the request may be duplicated on the client side - `handler`: an asynchronous function that must return a truthy value (for example, it should not be `undefined` or `null`) or the request may be duplicated on the client side.
::warning
The `handler` function should be **side-effect free** to ensure predictable behavior during SSR and CSR hydration. If you need to trigger side effects, use the [`callOnce`](/docs/api/utils/call-once) utility to do so.
::
- `options`: - `options`:
- `server`: whether to fetch the data on the server (defaults to `true`) - `server`: whether to fetch the data on the server (defaults to `true`)
- `lazy`: whether to resolve the async function after loading the route, instead of blocking client-side navigation (defaults to `false`) - `lazy`: whether to resolve the async function after loading the route, instead of blocking client-side navigation (defaults to `false`)