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?
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