From c8a5a4a4873cb18b59d152e54d1234cfe3b0d93c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=96z=C3=BCm=20Eldo=C4=9Fan?= Date: Thu, 9 Mar 2023 14:17:43 +0300 Subject: [PATCH] docs: update $fetch documentation (#19356) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Özüm Eldoğan Co-authored-by: Sébastien Chopin Co-authored-by: Sébastien Chopin --- docs/3.api/3.utils/$fetch.md | 42 ++++++++++++++++++++++++++++++------ 1 file changed, 36 insertions(+), 6 deletions(-) diff --git a/docs/3.api/3.utils/$fetch.md b/docs/3.api/3.utils/$fetch.md index 6026f3d409..180a2a868c 100644 --- a/docs/3.api/3.utils/$fetch.md +++ b/docs/3.api/3.utils/$fetch.md @@ -7,12 +7,42 @@ description: Nuxt uses ofetch to expose globally the $fetch helper for making HT Nuxt uses [ofetch](https://github.com/unjs/ofetch) to expose globally the `$fetch` helper for making HTTP requests within your Vue app or API routes. -::ReadMore{link="/docs/getting-started/data-fetching"} -:: - During server-side rendering, calling `$fetch` to fetch your internal [API routes](/docs/guide/directory-structure/server) will directly call the relevant function (emulating the request), **saving an additional API call**. -Note that `$fetch` is the preferred way to make HTTP calls in Nuxt 3 instead of [@nuxt/http](https://github.com/nuxt/http) and [@nuxtjs/axios](https://github.com/nuxt-community/axios-module) that are made for Nuxt 2. +However, using `$fetch` in components without wrapping it with `useAsyncData` causes fetching the data twice: initially on the server, then again on the client-side during hydration, because `$fetch` does not transfer state from the server to the client. Thus, the fetch will be executed on both sides because the client has to get the data again. -::NeedContribution -:: +We recommend to use [`useFetch`](https://nuxt.com/docs/api/composables/use-fetch) or [`useAsyncData`](https://nuxt.com/docs/api/composables/use-async-data) + `$fetch` to prevent double data fetching when fetching the component data. + +```vue + +``` + +:ReadMore{link="/docs/getting-started/data-fetching"} + +You can use `$fetch` for any method that are executed only on client-side. + +```vue + + + +``` + +`$fetch` is the preferred way to make HTTP calls in Nuxt instead of [@nuxt/http](https://github.com/nuxt/http) and [@nuxtjs/axios](https://github.com/nuxt-community/axios-module) that are made for Nuxt 2.