docs: add examples for useLazyFetch and useLazyAsyncData (#3418)

This commit is contained in:
Daniel Roe 2022-02-28 10:21:06 +00:00 committed by GitHub
parent 52d22feaea
commit 0958a61322
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -71,6 +71,24 @@ const { data } = await useAsyncData('count', () => $fetch('/api/count'))
This composable behaves identically to `useAsyncData` with the `lazy: true` option set. In other words, the async function does not block navigation. That means you will need to handle the situation where the data is `null` (or whatever value you have provided in a custom `default` factory function). This composable behaves identically to `useAsyncData` with the `lazy: true` option set. In other words, the async function does not block navigation. That means you will need to handle the situation where the data is `null` (or whatever value you have provided in a custom `default` factory function).
### Example
```vue
<template>
<div>
{{ pending ? 'Loading' : count }}
</div>
</template>
<script setup>
const { pending, data: count } = useLazyAsyncData('count', () => $fetch('/api/count'))
watch(count, (newCount) => {
// Because count starts out null, you won't have access
// to its contents immediately, but you can watch it.
})
</script>
```
## `useFetch` ## `useFetch`
Within your pages, components and plugins you can use `useFetch` to universally fetch from any URL. Within your pages, components and plugins you can use `useFetch` to universally fetch from any URL.
@ -121,6 +139,30 @@ const { data } = await useFetch('/api/count')
This composable behaves identically to `useFetch` with the `lazy: true` option set. In other words, the async function does not block navigation. That means you will need to handle the situation where the data is `null` (or whatever value you have provided in a custom `default` factory function). This composable behaves identically to `useFetch` with the `lazy: true` option set. In other words, the async function does not block navigation. That means you will need to handle the situation where the data is `null` (or whatever value you have provided in a custom `default` factory function).
### Example
```vue
<template>
<!-- you'll need to handle a loading state -->
<div v-if="pending">
Loading ...
</div>
<div v-else>
<div v-for="post in posts">
<!-- do something -->
</div>
</div>
</template>
<script setup>
const { pending, data: posts } = useLazyFetch('/api/posts')
watch(posts, (newPosts) => {
// Because posts starts out null, you won't have access
// to its contents immediately, but you can watch it.
})
</script>
```
## Isomorphic fetch ## Isomorphic fetch
When we call `fetch` in the browser, user headers like `cookie` will be directly sent to the API. When we call `fetch` in the browser, user headers like `cookie` will be directly sent to the API.