使用哪一个:$fetch、useAsyncData还是useFetch来进行Nuxt 3中的GET和POST请求?

huangapple go评论78阅读模式
英文:

Which to use: $fetch, useAsyncData or useFetch for GET and POST requests in Nuxt 3?

问题

I'm using Nuxt 3 with a Laravel API backend and trying to figure out which composable useAsyncData or useFetch, or just $fetch I should use for different API requests in CRUD and authentication.

The documentation says:

useFetch is the most straightforward way to handle data fetching in a component setup function. On the other hand, when wanting to make a network request based on user interaction, $fetch is almost always the right handler to go for.

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. We recommend to use useFetch or useAsyncData + $fetch to prevent double data fetching when fetching the component data.

You can use $fetch for any method that are executed only on client-side.

The only example I saw of a POST request in the documentation uses $fetch. Almost all other examples are GET requests that use useFetch.

Does this mean useFetch should generally be used for GET requests and $fetch for POST and PUT requests?

I'm confused because I've seen many tutorials of POST requests that use useFetch and GET requests that use $fetch.

Is it just easier to use useFetch for all requests since it has lots of Params, Options and Return Values that $fetch doesn't have, and also because it avoids the risk of fetching data twice in components?

In any case, is error handling for useFetch, $fetch, and useAsyncData the same? Can I just use the same error handling in all 3 that I would for the Fetch API?

英文:

I'm using Nuxt 3 with a Laravel API backend and trying to figure out which composable useAsyncData or useFetch, or just $fetch I should use for different API requests in CRUD and authentication.

The documentation says:

>useFetch is the most straightforward way to handle data fetching in a component setup function. On the other hand, when wanting to make a network request based on user interaction, $fetch is almost always the right handler to go for.

>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. We recommend to use useFetch or useAsyncData + $fetch to prevent double data fetching when fetching the component data.

>You can use $fetch for any method that are executed only on client-side.

The only example I saw of a POST request in the documentation uses $fetch. Almost all other examples are GET requests that use useFetch.

Does this mean useFetch should generally be used for GET requests and $fetch for POST and PUT requests?

I'm confused because I've seen many tutorials of POST requests that use useFetch and GET requests that use $fetch.

Is it just easier to use useFetch for all requests since it has lots of Params, Options and Return Values that $fetch doesn't have, and also because it avoids the risk of fetching data twice in components?

In any case, is error handling for useFetch, $fetch and useAsyncData the same? Can I just use the same error handling in all 3 that I would for the Fetch API?

答案1

得分: 1

以下是您要翻译的内容:

"When to use useFetch

The recommended way of using useFetch based on the documentation is in a component setup function, plugin, and route middleware. It is a straightforward way to handle data fetching without re-fetching or duplicate network calls, and it is a shortcut of useAsyncData + $fetch.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

// useAsyncData
const { data } = await useAsyncData('item', () => $fetch('/api/item'))

// useFetch ✅ Cleaner and easy to read.
const { data } = await useFetch('/api/item')

<!-- end snippet -->

> useAsyncData is a composable meant to be called directly in a setup
> function, plugin, or route middleware. It returns reactive composables
> and handles adding responses to the Nuxt payload so they can be passed
> from server to client without re-fetching the data on client side when
> the page hydrates.

useAsyncData documenation

>
> useFetch is a composable meant to be called directly in a setup
> function, plugin, or route middleware. It returns reactive composables
> and handles adding responses to the Nuxt payload so they can be passed
> from server to client without re-fetching the data on client side when
> the page hydrates.

useFetch documenation

So, when to use $fetch?

The recommended way based on the documentation to use the $fetch API is when posting a data to the event handler.

E.g.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

&lt;script setup lang=&quot;ts&quot;&gt;
function contactForm() {
  $fetch(&#39;/api/contact&#39;, {
    method: &#39;POST&#39;,
    body: { hello: &#39;world &#39;}
  })
}
&lt;/script&gt;

&lt;template&gt;
  &lt;button @click=&quot;contactForm&quot;&gt;Contact&lt;/button&gt;
&lt;/template&gt;

<!-- end snippet -->

You can also use $fetch API on the server/server routes.
e.g.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

export default defineEventHandler(async () =&gt; {
    const sendEmail = await $fetch(&#39;https//send-email.com/api/send-email&#39;)
    return sendEmail
})

<!-- end snippet -->

That is the recommended usage of these composables/API based on the nuxt documentation. But, in my personal use, using useFetch for posting data still works fine. It's just that it's not recommended.

For the error handling, based on the documentation it should be the same as they return the same values like, data, pending, refresh/execute, and status.

See aysncData return values

See useFetch return values

Hope that helps."

如有其他需要翻译的部分,请提供具体内容。

英文:

When to use useFetch

The recommended way of using useFetch based on the documentation is in a component setup function, plugin, and route middleware. It is a straightforward way to handle data fetching without re-fetching or duplicate network calls, and it is a shortcut of useAsyncData + $fetch.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

// useAsyncData
const { data } = await useAsyncData(&#39;item&#39;, () =&gt; $fetch(&#39;/api/item&#39;))

// useFetch ✅ Cleaner and easy to read.
const { data } = await useFetch(&#39;/api/item&#39;)

<!-- end snippet -->

> useAsyncData is a composable meant to be called directly in a setup
> function, plugin, or route middleware. It returns reactive composables
> and handles adding responses to the Nuxt payload so they can be passed
> from server to client without re-fetching the data on client side when
> the page hydrates.

useAsyncData documenation

>
> useFetch is a composable meant to be called directly in a setup
> function, plugin, or route middleware. It returns reactive composables
> and handles adding responses to the Nuxt payload so they can be passed
> from server to client without re-fetching the data on client side when
> the page hydrates.

useFetch documenation

So, when to use $fetch?

The recommended way based on the documentation to use the $fetch API is when posting a data to the event handler.

E.g.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

&lt;script setup lang=&quot;ts&quot;&gt;
function contactForm() {
  $fetch(&#39;/api/contact&#39;, {
    method: &#39;POST&#39;,
    body: { hello: &#39;world &#39;}
  })
}
&lt;/script&gt;

&lt;template&gt;
  &lt;button @click=&quot;contactForm&quot;&gt;Contact&lt;/button&gt;
&lt;/template&gt;

<!-- end snippet -->

You can also use $fetch API on the server/server routes.
e.g.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

export default defineEventHandler(async () =&gt; {
    const sendEmail = await $fetch(&#39;https//send-email.com/api/send-email&#39;)
    return sendEmail
})

<!-- end snippet -->

That is the recommended usage of these composables/API based on the nuxt documentation. But, in my personal use, using useFetch for posting data still works fine. It's just that it's not recommended.

For the error handling, based on the documentation it should be the same as they return the same values like, data, pending, refresh/execute, and status.

See aysncData return values

See useFetch return values

Hope that helps.

huangapple
  • 本文由 发表于 2023年8月5日 06:07:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76839341.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定