[useFetch] Component is already mounted, please use $fetch instead (in middleware)

I get this warning with useFetch in a middleware.
export default defineNuxtRouteMiddleware(async () => {
const { user } = useAuth()

const { data } = await useFetch('/api/auth/user')
user.value = data.value
})
export default defineNuxtRouteMiddleware(async () => {
const { user } = useAuth()

const { data } = await useFetch('/api/auth/user')
user.value = data.value
})
The documentation states: useFetch is a composable meant to be called directly in a setup function, plugin, or route middleware. I tried with useAsyncData too, but same erro. Do I have to make two separate middleware ? One using useFetch on server, and another using $fetch on client side ?? Or can I just use usefetch when process.server and $fetch when process.client ?
5 Replies
Likonima
Likonimaβ€’10mo ago
you should use $fetch here
! GhostvOne.tv πŸ‘»πŸ‡«πŸ‡·
I'm here for explanations. πŸ™‚ (I already read the error) Using $fetch in middleware is calling twice. First time on server, second time when the page is renderer the first time. Maybe could i use
if (useNuxtApp().isHydrating) return
if (useNuxtApp().isHydrating) return
Likonima
Likonimaβ€’10mo ago
oh interesting that the docs state useFetch is for middleware too. Didn't know.
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.
makes sense then ig
! GhostvOne.tv πŸ‘»πŸ‡«πŸ‡·
That's why I came here .
Zeeeth
Zeeethβ€’10mo ago
Im sorry you havn't gotten any real help. I do almost the same thing that you do, but i do not use useFetch in my middleware, but $fetch as stated by the warning. What i do to avoid the multi-call is to store the user in a store. You may use the useStore or some other store manager. That way, you can check if the user is already fetched, end if not refresh the user into your store i also have separated this into two different middlewares: * 10.auth.global.ts * 20.user.global.ts the auth-middleware handle the authentication and user-middleware make sure the userStore is populated with the current user if the user is authenticated
Want results from more Discord servers?
Add your server