Composing queries with queryOptions
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 typesconst 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,
})