TanStackT
TanStack2y ago
4 replies
slow-yellow

Composing queries with queryOptions

There is a
queryOptions
function that accept the same props as
useQuery
etc. This would allow defining my queryKey and
queryFn
properties independent of usage while still resolve the correct types.
https://tanstack.com/query/latest/docs/framework/vue/guides/query-options

I want to be able to compose multiple pieces together easily but I'm having a lot of type issues.

I'm wondering if anyone has been able to get a similar approach to work or if there are some other types I can use that don't require me having to define all the types by hand.

A rough example might be something like the following:

`` // Returns result of queryOptions` with correctly inferred types
const vendorQueryOptions = (id: MaybeRef<number | undefined>): UseQueryOptions => {
return queryOptions({
queryKey: ['vendors', id],
queryFn: () => {
const primitiveId = unref(id)
if (!primitiveId) throw Error('Missing id')
return api.getVendorById(primitiveId)
},
})
}


const testId = ref(1)

// Valid: can use queryOptions output directly
const q = useQuery({
...vendorQueryOptions(testId)
})

// Valid: can use queryOptions output directly with plain objects
const q = useQuery({
...vendorQueryOptions(testId),
...{enabled: computed(() => !!testId.value)},
})

// Invalid: can't use queryOptions output more than once (I assume inferred types conflict)
const q = useQuery({
...vendorQueryOptions(testId),
...queryOptions({enabled: computed(() => !!testId.value)}),
})

// Invalid: can't use object typed with UseQueryOptions (I assume inferred types conflict)
const someOptions: UseQueryOptions = {enabled: computed(() => !!testId.value)}
const q = useQuery({
...vendorQueryOptions(testId),
...someOptions,
})
One of the best ways to share queryKey and queryFn between multiple places, yet keep them co-located to one another, is to use the queryOptions helper. At runtime, this helper just returns whatever you pass into it, but it has a lot of advantages when using it with TypeScript. You can define all possible options for a query in one place, and yo...
Was this page helpful?