T
TanStack5mo ago
rising-crimson

Using vue query outside of setup functions

Does anybody have a working example of how to use vue query composable outside of the vue component? For example inside an pinia action. I can't find any example of this in the docs or online. Thanks!
3 Replies
eager-peach
eager-peach4mo ago
queryClient.fetchQuery(queryOptions)
sensitive-blue
sensitive-blue4mo ago
You can use something like the following composable:
export function useEntity() {

function fetchEntity(entityId: MaybeRefOrGetter<string>) {
return useQuery({
queryKey: ['entity', { entityId }],
queryFn: () => yourQueryOrApi({ id: toValue(entityId) }),
enabled: computed(() => !!toValue(entityId)),
})
}

return {
fetchEntity
}
}
export function useEntity() {

function fetchEntity(entityId: MaybeRefOrGetter<string>) {
return useQuery({
queryKey: ['entity', { entityId }],
queryFn: () => yourQueryOrApi({ id: toValue(entityId) }),
enabled: computed(() => !!toValue(entityId)),
})
}

return {
fetchEntity
}
}
environmental-rose
environmental-rose7d ago
I also struggled with this. useQuery needs to run inside of an 'injection context'. Additionally, it will also warn if not inside an 'effect scope'. ie. you need to have an app, and you need to already be inside a component or composable. For us this surfaced in tests, because our composables can otherwise be tested as standalone functions without any setup. Here's a simple example:
import { createApp, effectScope } from "vue"
import { VueQueryPlugin, QueryClient, useQuery } from "@tanstack/vue-query"
import App from "./App.vue"

const app = createApp(App)

app.use(VueQueryPlugin, { queryClient: new QueryClient() })

app.runWithContext(() => {
effectScope().run(() => {
useQuery({
queryKey: ["ping"],
queryFn: async () => "pong",
})
})
})
import { createApp, effectScope } from "vue"
import { VueQueryPlugin, QueryClient, useQuery } from "@tanstack/vue-query"
import App from "./App.vue"

const app = createApp(App)

app.use(VueQueryPlugin, { queryClient: new QueryClient() })

app.runWithContext(() => {
effectScope().run(() => {
useQuery({
queryKey: ["ping"],
queryFn: async () => "pong",
})
})
})

Did you find this page helpful?