N
Nuxt7mo ago
robertb45

Using custom $fetch outside Nuxt Context (Pinia Store) produces error but still works

Hello! Quick background, I followed this guide: https://notes.atinux.com/nuxt-custom-fetch on how to create a custom $fetch implementation, and for now it works on some parts of my app calling it inside some Pinia functions, but now I stumbled upon an error when using it like this: This is a function inside a useAuthStore(), which is called by an initStore plugin which only does that.
async function fetchUser() {
loading.value = true
try {
const { getToken } = useNuxtApp().$authCookie
if (!getToken()) return
const response = await $api<User>('/auth/users/me')
user.value = response
await fetchWorkspaces()
return response
} catch (error: any) {
console.log('error:', error.data?.message ?? error.cause)
return { error }
} finally {
loading.value = false
}
}
async function fetchUser() {
loading.value = true
try {
const { getToken } = useNuxtApp().$authCookie
if (!getToken()) return
const response = await $api<User>('/auth/users/me')
user.value = response
await fetchWorkspaces()
return response
} catch (error: any) {
console.log('error:', error.data?.message ?? error.cause)
return { error }
} finally {
loading.value = false
}
}
And it calls the fetchWorkspaces() function which is:
async function fetchWorkspaces() {
try {
const response = await $api<PagedApiResponse<Workspace>>('/workspaces', {
query: { limit: 'all' }
})
// useCurrentWorkspaceStore().setupWorkspace()
return response
} catch (error: any) {
console.log('error:', error)
return { error }error.cause)
}
}
async function fetchWorkspaces() {
try {
const response = await $api<PagedApiResponse<Workspace>>('/workspaces', {
query: { limit: 'all' }
})
// useCurrentWorkspaceStore().setupWorkspace()
return response
} catch (error: any) {
console.log('error:', error)
return { error }error.cause)
}
}
But the problem that I'm getting is an error in the console/terminal which is: [nuxt] A composable that requires access to the Nuxt instance was called outside of a plugin, Nuxt hook, Nuxt middleware, or Vue setup function. This is probably not a Nuxt bug and also in browser console:
ssr:warn Cannot stringify arbitrary non-POJOs Error
at log (node_modules/@nuxt/devalue/dist/devalue.mjs)
ssr:warn Cannot stringify arbitrary non-POJOs Error
at log (node_modules/@nuxt/devalue/dist/devalue.mjs)
I've been doing a little research on this but I can't understand why calling the fetchWorkspaces method gives this error, while the fetchUser method doesn't, even though I get the data back, if I do a console.log of the response of fetchWorkspaces, the data is there. Thanks in advance
1 Reply
dwol
dwol7mo ago
Pinia 🍍
Intuitive, type safe, light and flexible Store for Vue
Want results from more Discord servers?
Add your server