T
TanStack12mo ago
rare-sapphire

Pass initial data in a server component

Hi. I'd like to achive something like this using nextjs app router and tanstack query: 1. Root layout renders and fetches initial user vip level by session id from cookies 2. Root layout renders a QueryClientProvider and passes just fetched level - lets say bronze to the provider 3. Client component somewhere else uses hook useVipLevel which should never be loading because there should be initial data passed on the first user enter even before client components render How can I pass this initial data to query client and then make some type assertions inside useVipLevel to tell the useQuery that we always have data?
const MainLayout = async ({
children
}: {
children: React.ReactNode;
}) => {
const vipLevel = await getVipLevel();
const MainLayout = async ({
children
}: {
children: React.ReactNode;
}) => {
const vipLevel = await getVipLevel();
import { useQuery } from '@tanstack/react-query';
import { getVipLevel } from './get-vip-level';

export function useVipLevel() {
return useQuery({
queryKey: ['vip-level'],
queryFn: getVipLevel
});
}
import { useQuery } from '@tanstack/react-query';
import { getVipLevel } from './get-vip-level';

export function useVipLevel() {
return useQuery({
queryKey: ['vip-level'],
queryFn: getVipLevel
});
}
1 Reply
xenial-black
xenial-black12mo ago
this is all documented in the ssr and advanced ssr guides in the docs

Did you find this page helpful?