Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com> Co-authored-by: Daniel Roe <daniel@roe.dev>
2.3 KiB
title | description | links | |||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
$fetch | Nuxt uses ofetch to expose globally the $fetch helper for making HTTP requests. |
|
Nuxt uses ofetch to expose globally the $fetch
helper for making HTTP requests within your Vue app or API routes.
::callout{icon="i-ph-rocket-launch-duotone"}
During server-side rendering, calling $fetch
to fetch your internal API routes will directly call the relevant function (emulating the request), saving an additional API call.
::
::callout{color="blue" icon="i-ph-info-duotone"}
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.
::
We recommend to use useFetch
or useAsyncData
+ $fetch
to prevent double data fetching when fetching the component data.
<script setup lang="ts">
// During SSR data is fetched twice, once on the server and once on the client.
const dataTwice = await $fetch('/api/item')
// During SSR data is fetched only on the server side and transferred to the client.
const { data } = await useAsyncData('item', () => $fetch('/api/item'))
// You can also useFetch as shortcut of useAsyncData + $fetch
const { data } = await useFetch('/api/item')
</script>
:read-more{to="/docs/getting-started/data-fetching"}
You can use $fetch
for any method that are executed only on client-side.
<script setup lang="ts">
function contactForm() {
$fetch('/api/contact', {
method: 'POST',
body: { hello: 'world '}
})
}
</script>
<template>
<button @click="contactForm">Contact</button>
</template>
::callout
$fetch
is the preferred way to make HTTP calls in Nuxt instead of @nuxt/http and @nuxtjs/axios that are made for Nuxt 2.
::