Example of using useQuery inside the vue-router beforeEach callback. #6987
-
Im seeing this issue being merge #5703 but i cant figure out how to use it. Is there an example on how to do this? right now this in my main.ts import { VueQueryPlugin, QueryClient, type VueQueryPluginOptions } from '@tanstack/vue-query'
const queryClient = new QueryClient();
const vueQueryOptions: VueQueryPluginOptions = {
queryClientConfig: {
defaultOptions: {
queries: {
gcTime: 1000 * 60 * 60 * 24,
// staleTime: 1000 * 10,
},
},
},
queryClient
}
app.provide('queryClient', queryClient)
app.use(VueQueryPlugin, vueQueryOptions); and my router router.beforeEach(async (route) => {
const queryClient = inject('queryClient') as QueryClient;
const getMe = useQuery({
queryKey: ['auth', 'getMe'],
queryFn: async () => {
const data = await authService().getMe()
return AuthUserModel(data.data)
},
retry: false,
staleTime: DEFAULT_STALE_TIME,
}, queryClient)
if (route.meta.requiresAuth && !getMe.data.value?.id) {
await getMe.refetch()
if (!getMe.data.value?.id) {
return { name: 'auth-login' }
}
}
}) But i keep getting these warnings:
|
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
Fixed it for now by doing it completely different: router.beforeEach(async (route) => {
const queryClient = inject('queryClient', new QueryClient());
const data = queryClient.getQueryData(['auth', 'getMe'])
const parsed = AuthUserResource.safeParse(data)
if (route.meta.requiresAuth && !parsed.success) {
try {
const {data} = await authService().getMe()
queryClient.setQueryData(['auth', 'getMe'], AuthUserModel(data))
} catch {
return { name: 'auth-login' }
}
}
}) But is this the preferred way of doing this? since im not really using the useQuery function anymore. |
Beta Was this translation helpful? Give feedback.
-
i think i got it, Shouldn't use the useQuery stuff since that is only for components (i guess) but fetchQuery should work: router.beforeEach(async (route) => {
const queryClient = inject('queryClient', new QueryClient())
const data = await queryClient.fetchQuery({
queryKey: ['auth', 'getMe'],
queryFn: async () => {
const data = await authService().getMe()
return AuthUserModel(data.data)
},
})
if (route.meta.requiresAuth && !data.id) {
return { name: 'auth-login' }
}
}) with these options so it doesnt need to refetch everytime someone navigates to a different page
|
Beta Was this translation helpful? Give feedback.
-
You need to wrap |
Beta Was this translation helpful? Give feedback.
i think i got it, Shouldn't use the useQuery stuff since that is only for components (i guess) but fetchQuery should work:
with these options so it doesnt need to refetch everytime someone navigates to a different page