T
TanStack•11mo ago
ratty-blush

ensureQueryData vs prefetchQuery

Hello guys! I'm trying to integrate react-query with tanstack router and I'm a bit confused about ensureQueryData and prefetchQuery
export const Route = createFileRoute('/posts')({
loader: ({ context: { queryClient } }) => {
return queryClient.ensureQueryData(postsQueryOptions())
},
errorComponent: PostErrorComponent,
pendingComponent: PendingComponent,
component: PostsComponent
})

function PostsComponent() {
const { data: posts } = useSuspenseQuery(postsQueryOptions())

return...
}
export const Route = createFileRoute('/posts')({
loader: ({ context: { queryClient } }) => {
return queryClient.ensureQueryData(postsQueryOptions())
},
errorComponent: PostErrorComponent,
pendingComponent: PendingComponent,
component: PostsComponent
})

function PostsComponent() {
const { data: posts } = useSuspenseQuery(postsQueryOptions())

return...
}
VS
export const Route = createFileRoute('/posts')({
loader: ({ context: { queryClient } }) => {
return queryClient.prefetchQuery(postsQueryOptions())
},
errorComponent: PostErrorComponent,
pendingComponent: PendingComponent,
component: PostsComponent
})

function PostsComponent() {
const { data: posts } = useSuspenseQuery(postsQueryOptions())

return...
}
export const Route = createFileRoute('/posts')({
loader: ({ context: { queryClient } }) => {
return queryClient.prefetchQuery(postsQueryOptions())
},
errorComponent: PostErrorComponent,
pendingComponent: PendingComponent,
component: PostsComponent
})

function PostsComponent() {
const { data: posts } = useSuspenseQuery(postsQueryOptions())

return...
}
Should I call prefetchQuery or ensureQueryData? I saw that ensureQueryData means getQueryData ?? fetchQuery but i'm still confused 😄 Thank you for taking your time to check this!
6 Replies
eastern-cyan
eastern-cyan•11mo ago
Return ensureQueryData if you want the loader to block, prefetchQuery and don't return the promise otherwise Dominick went into more detail here https://discord.com/channels/719702312431386674/1003327027849474198/1313780863430819871
ratty-blush
ratty-blushOP•11mo ago
Ok. Thank you for the link. So ensure is what I need Do I need to await it? Or just return it In order to show the pending component
eastern-cyan
eastern-cyan•11mo ago
In this case there is no difference. return promise vs return await promise is a Google search of it's own
eastern-cyan
eastern-cyan•11mo ago
Stack Overflow
Difference between return await promise and return promise
Given the code samples below, is there any difference in behavior, and, if so, what are those differences? return await promise async function delay1Second() { return (await delay(1000)); } re...
ratty-blush
ratty-blushOP•11mo ago
Thank you!
eastern-cyan
eastern-cyan•11mo ago
No problem

Did you find this page helpful?