There are three main components for implementing data fetching in Nuxt.js:
useFetch - go to for data fetching. A wrapper of useAsyncData and $fetch .useAsyncData - wrapping async logic and return once resolved.$fetch - Under the hood is ofetch.Use this in setup components, plugins, or route middleware.
useFetch is server-side rendered by default but also automatically switches to client-side fetching when needed.
You can force useFetch to execute client-side by using the key option.
const { data, error } = useFetch('/api/endpoint', {
credentials: 'include',
key: 'client-fetch',
});
<aside> ✅
In my case, I need to include credentials along with my requests, which credentials(cookies) only live in the browser (client-side environment), so I had to use $fetch to implement the queries correctly. (more straightforward)
</aside>
useAsyncData allows greater control over how the data is fetched asynchronously.When you want multiple $fetch in a composable.
Sometimes, API requests might fail, and you'd want to retry the request a certain number of times before giving up.
When a CMS or a third party provides their own query layer.
useFetch offers.<aside> ✅
Can also use useAsyncData for sending requests with client-side only credentials(cookies). Include the condition for process.client should do the work.
</aside>