docs: update data fetching page to read more ergonomically

This commit is contained in:
Nishant Aanjaney Jalan 2024-09-15 22:07:31 +05:30 committed by GitHub
parent 21b2cc736e
commit 3404589337
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -8,9 +8,9 @@ Nuxt comes with two composables and a built-in library to perform data-fetching
In a nutshell:
- [`useFetch`](/docs/api/composables/use-fetch) is the most straightforward way to handle data fetching in a component setup function.
- [`$fetch`](/docs/api/utils/dollarfetch) is great to make network requests based on user interaction.
- [`useAsyncData`](/docs/api/composables/use-async-data), combined with `$fetch`, offers more fine-grained control.
- [`$fetch`](/docs/api/utils/dollarfetch) is the simplest way to make a network request.
- [`useFetch`](/docs/api/composables/use-fetch) is the SSR-friendly version of `$fetch` that prevent hydration mismatches.
- [`useAsyncData`](/docs/api/composables/use-async-data) is similar to `useFetch` but offers more fine-grained control.
Both `useFetch` and `useAsyncData` share a common set of options and patterns that we will detail in the last sections.
@ -30,6 +30,34 @@ The payload is a JavaScript object accessible through [`useNuxtApp().payload`](/
Use the [Nuxt DevTools](https://devtools.nuxt.com) to inspect this data in the **Payload tab**.
::
```vue [app.vue]
<script setup lang="ts">
const { data } = await useFetch('/api/data')
async function handleFormSubmit() {
const res = await $fetch('/api/submit', {
method: 'POST',
body: {
// My form data
}
})
}
</script>
<template>
<div v-if="data == null">
No data
</div>
<div v-else>
<form @submit="handleFormSubmit">
<!-- form input tags -->
</form>
</div>
</template>
```
In the example above, `useFetch` would make sure that the API call would occur in the server and properly forward the request to the browser. `$fetch` has no such mechanism and is a better option to use when the request is solely made from the browser.
### Suspense
Nuxt uses Vues [`<Suspense>`](https://vuejs.org/guide/built-ins/suspense) component under the hood to prevent navigation before every async data is available to the view. The data fetching composables can help you leverage this feature and use what suits best on a per-calls basis.
@ -40,7 +68,7 @@ You can add the [`<NuxtLoadingIndicator>`](/docs/api/components/nuxt-loading-ind
## `useFetch`
The [`useFetch`](/docs/api/composables/use-fetch) composable is the most straightforward way to perform data fetching.
The [`useFetch`](/docs/api/composables/use-fetch) composable is the most straightforward way to perform SSR-safe data fetching.
```vue twoslash [app.vue]
<script setup lang="ts">