NextJS prefetch using HydrationBoundary + client component useQuery fetches in client upon mount #7184
-
So, I've followed the docs on how to setup the RSC/NextJS 14 in combination with TanStack Query. My I have a page at import PublicRegisterClientTable from "@/components/patterns/public-register-table.client"
import PublicRegisterFilters from "@/types/PublicRegisterFilters"
import { getCertificates } from "@/utils/public-register"
import {
HydrationBoundary,
QueryClient,
dehydrate,
} from "@tanstack/react-query"
import * as React from "react"
export type PublicRegisterServerTableProps =
React.HTMLAttributes<HTMLTableElement>
const PublicRegisterServerTable = async ({
children,
...restProps
}: PublicRegisterServerTableProps) => {
const queryClient = new QueryClient()
await queryClient.prefetchQuery({
queryKey: ["public-register"],
queryFn: getCertificates,
})
console.log(dehydrate(queryClient)) // This logs `{ mutations: [], queries: [] }`
return (
<HydrationBoundary state={dehydrate(queryClient)}>
<PublicRegisterClientTable {...restProps}>
{children}
</PublicRegisterClientTable>
</HydrationBoundary>
)
}
export default PublicRegisterServerTable This is my client component: "use client"
import { getErrorMessage } from "@/utils/error"
import { getCertificates } from "@/utils/public-register"
import { cn } from "@/utils/tailwind"
import { useQuery } from "@tanstack/react-query"
import * as React from "react"
export type PublicRegisterClientTableProps =
React.HTMLAttributes<HTMLTableElement>
const PublicRegisterClientTable = ({
className,
children,
...restProps
}: PublicRegisterClientTableProps) => {
const { data, error, isPending } = useQuery({
queryKey: ["public-register"],
queryFn: getCertificates,
})
return (
<table className={cn("", className)} {...restProps}>
<tbody>
{isPending ? (
<tr>
<td>Loading...</td>
</tr>
) : error ? (
<tr>
<td>{getErrorMessage(error)}</td>
</tr>
) : (
data.map(certificate => (
<tr key={certificate.coid}>
<td>
<pre>
<code>{JSON.stringify(certificate, undefined, "\t")}</code>
</pre>
</td>
</tr>
))
)}
</tbody>
</table>
)
}
export default PublicRegisterClientTable I'm using the exact same setup as the docs describe, except that I do not prefetch in Using this setup, data is immediately fetched in the client component upon mount. This should not happen. There is a |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Okay so I'm dumb. Apparently my |
Beta Was this translation helpful? Give feedback.
Okay so I'm dumb. Apparently my
getCertificates
function didn't work in the server component, as it was using a relative URL. It failed silently. Closing this, it's working as expected now.