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

1

9

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?

Russi answered 4/8, 2023 at 22:7 Comment(0)
R
12

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.

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

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

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 documentation

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 documentation

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.

<script setup lang="ts">
function contactForm() {
  $fetch('/api/contact', {
    method: 'POST',
    body: { hello: 'world '}
  })
}
</script>

<template>
  <button @click="contactForm">Contact</button>
</template>

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

export default defineEventHandler(async () => {
    const sendEmail = await $fetch('https//send-email.com/api/send-email')
    return sendEmail
})

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.

Rolan answered 4/8, 2023 at 23:29 Comment(6)
Nuxt team member here. It is important to note that useFetch is reactive (thus re-triggering when dependencies change) and might send more request than wanted. This can be undesired behavior (e.g. when submitting a login form on every keystroke after the first request failed because the password was wrong).Hollingsworth
@manniL, If I understood your comment correctly. Any methods that are executed online on the client-side, you can use $fetch. Similar to my example when posting a data to the event handler?Rolan
You can use $fetch or useFetch for these, yes. But with $fetch, it is guaranteed to be a "one-off" call. useFetch can have unwanted side effects when e.g. sending a POST request - as it will send the request again in case the dependencies (e.g. username) change.Hollingsworth
So it is not a good idea to use useFetch in another composable? 🤔Intercellular
I'm from Brazil. Thanks for the answer.Rudolf
For API routes event handler & client event handler always use $fetch.Bookshelf

© 2022 - 2024 — McMap. All rights reserved.