TanStackT
TanStack13mo ago
2 replies
primary-violet

`queryClient.prefetchQuery` is not storing the data in cache when using in Next.js with RPC calls

I am using Next.js with Hono as the backend.


Here's how I am prefetching the data on server component

const Posts = async () => {
  const session = await auth()

  if (!session?.user) {
    return <Unauthorized />
  }

  const queryClient = new QueryClient()
  await queryClient.prefetchQuery(getPostQueryOptions)

  return (
    <>
      <Toaster />
      <h1 className="scroll-m-20 text-4xl font-extrabold tracking-tight lg:text-5xl">
        Posts
      </h1>
      <HydrationBoundary state={dehydrate(queryClient)}>
        <PostList />
      </HydrationBoundary>
      <div>
        <CreatePostForm userId={session?.user.id || ''} />
      </div>
    </>
  )
}


Here's the hooks and Hono RPC calls

export const getPostQueryOptions = queryOptions({
  queryKey: ['posts'],
  queryFn: getPosts,
  staleTime: 10 * 1000,
})

export function useGetPosts() {
  return useQuery(getPostQueryOptions)
}



export async function getPosts(): Promise<
  Array<Zod.infer<typeof selectPostSchema>>
> {
  // const response = await fetch('/api/posts')
  const response = await client.api.posts.$get()

  if (!response.ok) {
    throw new Error(`Request failed with status: ${response.status}`)
  }

  return response.json()
}


What am I missing
Was this page helpful?