N
Nuxt5mo ago
abd

useFetch && $fetch

hello, I have a page component with a date picker. when the page component loads it is fetching data for the default date today() for the user using usefetch The user can then select a different date to select data for that date. I get this warning in the console Component is already mounted, please use $fetch instead. This is my component code
const fetchContent = async (newDateRange) => {
isLoading.value = true
const { data } = await useFetch("/api/content", {
method: "POST",
body: JSON.stringify({
startDate: newDateRange.start,
endDate: newDateRange.end,
}),
})

presentContent.value = data.value
isLoading.value = false
}
const fetchContent = async (newDateRange) => {
isLoading.value = true
const { data } = await useFetch("/api/content", {
method: "POST",
body: JSON.stringify({
startDate: newDateRange.start,
endDate: newDateRange.end,
}),
})

presentContent.value = data.value
isLoading.value = false
}
What is the correct pattern to use?
3 Replies
sexyGaming - Kiroma
As far as I understood it: useFetch for everything on the server and $fetch for everything a user action may trigger. But I think you can use the refresh nad/or execute method you get from the useFetch in the client side code to also refetch. Fun part is also, that you can use $fetch on server side but it will not send your whole request headers of the client to the underlying endpoint you request to (leading to no user session if doing internal routing). Related issue to my last comment: https://github.com/nuxt/nuxt/issues/24813
GitHub
$fetch: use useRequestFetch() when calling internal API during ...
Describe the feature When having API routes in Nuxt with authentication (using H3 useSession or nuxt-auth-utils), we need to forward the cookie to the API routes when fetching the data on SSR. Not ...
sexyGaming - Kiroma
Just in case you have an authentication system and now use $fetch and sometimes see an unauthenticated user in your logs even though you are logged in, thats why I mention it... SPent a while on figuring that out last time, saving you the trouble. Also in terms of SSR its a good idea to use useAsyncData because it will not lead to 2 requests, as it will get hydrated into the client instead of having both to call it initially. If its used both on server and client you can always use both by doing an if(import.meta.client) or if(import.meta.server) and thus do a useFetch or $fetch. But maybe I am exeggarting the problem because I myself did not 100% understood how to use the fetching in gerneral correctly 😄
abd
abdOP4mo ago
thank you
Want results from more Discord servers?
Add your server