T
TanStack2mo ago
wise-white

Prefetch query with parameters

I have a page.tsx that calls a function.
await queryClient.prefetchQuery({
queryKey: ['posts'],
queryFn: getPosts,
})
await queryClient.prefetchQuery({
queryKey: ['posts'],
queryFn: getPosts,
})
What if the getPosts call here, is subject to the params in the query string of the user landing on the page? Say "category" is a filter and I want to only show those.
await queryClient.prefetchQuery({
queryKey: ['posts'],
queryFn: getPosts({ category: "Cooking" }),
})
await queryClient.prefetchQuery({
queryKey: ['posts'],
queryFn: getPosts({ category: "Cooking" }),
})
Throws an error because now I am calling this function in the first render server side. It gives:
Error: Server Functions cannot be called during initial render. This would create a fetch waterfall. Try to use a Server Component to pass data to Client Components instead.
Error: Server Functions cannot be called during initial render. This would create a fetch waterfall. Try to use a Server Component to pass data to Client Components instead.
So what is the pattern that should be used here?
2 Replies
ratty-blush
ratty-blush2mo ago
seems like you are using Next? In that case prefetch query in server component then handle user interaction separately.
const queryClient = new QueryClient()

// Prefetch on server
await queryClient.prefetchQuery({
queryKey: ['posts'],
queryFn: getPosts
})

return (
<HydrationBoundary state={dehydrate(queryClient)}>
<PostsList />
</HydrationBoundary>
)
const queryClient = new QueryClient()

// Prefetch on server
await queryClient.prefetchQuery({
queryKey: ['posts'],
queryFn: getPosts
})

return (
<HydrationBoundary state={dehydrate(queryClient)}>
<PostsList />
</HydrationBoundary>
)
continuing-cyan
continuing-cyan2mo ago
You add it to query key itself
function Todos({ todoId }) {
const result = useQuery({
queryKey: ['todos', todoId],
queryFn: () => fetchTodoById(todoId),
})
}
function Todos({ todoId }) {
const result = useQuery({
queryKey: ['todos', todoId],
queryFn: () => fetchTodoById(todoId),
})
}
https://tanstack.com/query/latest/docs/framework/react/guides/query-keys Add all the filtering, sorting, searching to query key

Did you find this page helpful?