T
TanStack•2y ago
afraid-scarlet

Equivalent for query v4

Hi all in the doc of router to use tanstack query with router we got this example :
const postsQueryOptions = queryOptions({
queryKey: ['posts'],
queryFn: () => fetchPosts(),
})
export const Route = createFileRoute('/posts')({
// Use the `loader` option to ensure that the data is loaded
loader: () => queryClient.ensureQueryData(postsQueryOptions),
component: () => {
// Read the data from the cache and subscribe to updates
const posts = useSuspenseQuery(postsQueryOptions)
return (
<div>
{posts.map((post) => (
<Post key={post.id} post={post} />
))}
</div>
)
},
})
const postsQueryOptions = queryOptions({
queryKey: ['posts'],
queryFn: () => fetchPosts(),
})
export const Route = createFileRoute('/posts')({
// Use the `loader` option to ensure that the data is loaded
loader: () => queryClient.ensureQueryData(postsQueryOptions),
component: () => {
// Read the data from the cache and subscribe to updates
const posts = useSuspenseQuery(postsQueryOptions)
return (
<div>
{posts.map((post) => (
<Post key={post.id} post={post} />
))}
</div>
)
},
})
Is there an equivalent of use case but with the V4 of Query as the queryOptions is a feature of the V5 and i can't upgrade to v5 due to client project restriction
5 Replies
fascinating-indigo
fascinating-indigo•2y ago
you can use it without calling queryOptions - it doesn't do anythign at runtime, it's only for TS:
const postsQueryOptions = {
queryKey: ['posts'],
queryFn: () => fetchPosts(),
}
const postsQueryOptions = {
queryKey: ['posts'],
queryFn: () => fetchPosts(),
}
type inference and safety will be a bit worse; you can also just copy-paste the queryOptions function from v5 to your repo (maybe some type parameters would need adjustment and DataTag doesn't exist). It's one line of code and ~50 lines of types 🙂 https://github.com/TanStack/query/blob/03048e3776041ff5f5776b1b739c18183aa7e33a/packages/react-query/src/queryOptions.ts
GitHub
query/packages/react-query/src/queryOptions.ts at 03048e3776041ff5f...
🤖 Powerful asynchronous state management, server-state utilities and data fetching for the web. TS/JS, React Query, Solid Query, Svelte Query and Vue Query. - TanStack/query
afraid-scarlet
afraid-scarletOP•2y ago
@TkDodo 🔮 is the use of useSuspenseQuery is mandatory or we could pass by const posts = Route.useLoaderData();
ratty-blush
ratty-blush•2y ago
If you do not want to use useSuspenseQuery just use useQuery. If you just use useLoaderData, there's a big chance that you get stale data (Checkout the docs about ensureQueryData) and you don't have the great Features of tanstack Query.
fascinating-indigo
fascinating-indigo•2y ago
You can use normal useQuery, the thing about suspense is that data is never undefined
afraid-scarlet
afraid-scarletOP•2y ago
oh ok thank you for the explaination

Did you find this page helpful?