QueryOptions for cross-framework library #10735
Replies: 1 comment
-
|
The pattern you're looking for is to build your library on top of Pattern: // @mylib/query-core (depends only on @tanstack/query-core)
import type { QueryOptions } from '@tanstack/query-core'
export const userQueryOptions = (userId: string): QueryOptions => ({
queryKey: ['users', userId],
queryFn: () => fetchUser(userId),
staleTime: 1000 * 60 * 5,
})Then in consuming apps, no adapter shim needed: // React app
import { useQuery } from '@tanstack/react-query'
import { userQueryOptions } from '@mylib/query-core'
const { data } = useQuery(userQueryOptions(userId))// Vue app
import { useQuery } from '@tanstack/vue-query'
import { userQueryOptions } from '@mylib/query-core'
const { data } = useQuery(userQueryOptions(userId))If you want import { queryOptions } from '@tanstack/query-core'
export const userQueryOptions = (userId: string) =>
queryOptions({
queryKey: ['users', userId],
queryFn: () => fetchUser(userId),
})This gives you full type inference and the resulting object is accepted by all framework adapters since they all share the same underlying type. You don't need separate |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I see what looks like nearly duplicate code in
react-query,lit-query,vue-queryfor theirqueryOptionsmethod definitions. Not precisely the same, but darn close.If I'm developing a library using
tanstack-queryto fetch data from my service, is there a pattern to conveniently produce my own@mylib/query-coreimplementation that producesoptionsobjects that includequeryKeyandqueryFnthat makes it easy to then produce@mylib/query-reactand@mylib/query-vue, etc. Seems like that's a potential benefit of the pattern (if not the outright goal). Is there a library doing this effectively/efficiently that I should take a look at?Beta Was this translation helpful? Give feedback.
All reactions