I have a Server component that follows the documentation to prefetch a query and hydrates it in my page.tsx:
export default async function ListingDetailPage({
params,
}: {
params: { reference: number };
}) {
const queryClient = new QueryClient();
await queryClient.prefetchQuery({
queryKey: ["listing", params.reference],
queryFn: fetchListingByReference,
staleTime: 1000 * 60 * 5,
});
return (
<HydrationBoundary state={dehydrate(queryClient)}>
<ClientPage />
</HydrationBoundary>
);
}
I am also using the Next.JS generateMetadata function in the same page.tsx file to generate the metadata:
export async function generateMetadata({
params,
}: {
params: { reference: number };
}): Promise<Metadata> {
const listing = await fetchListingByReference({
queryKey: ["listing", params.reference],
});
return generateListingMetaTags(listing);
}
Is there any way to only run fetchListingByReference once on the server and have it cached across requests, to both generate the metadata and hydrate the client? From the documentation I understand that prefetchQuery does not return the data. So can I run useQuery instead of prefetchQuery and use that to hydrate the client?
And then how can I run it once to use the same in generatemetadata? Do I just run useQuery again in the generateMetadata function and it will only run once?
Also, is there a way to see whether a query was prefetched successfully in the react query dev tool?