TanStackT
TanStackโ€ข13mo agoโ€ข
9 replies
full-green

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...
}  

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...
}  


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!
Was this page helpful?