T
TanStack11mo ago
fascinating-indigo

How to avoid double fetching in parallel server components. How to make use of caching

I want to fetch my data only once instead of twice when I load data that I use on the server to redirect and then pass down as initial data to my client components. A lot of sources say it is a bad practice to pass down props from a layout.tsx to the children. So it is no option for me to fetch in a layout.tsx file and pass it down to the children. Also while trying this I experienced a few errors. Here a few sources to that: https://stackoverflow.com/questions/74573236/pass-props-to-page-jsx-child-from-root-layout-next-js-13/77983273#77983273 So how can I make sure it's not refetching twice if I have two parallel server components? The await queryClient.prefetchQuery({ is no option as I need to access the data as it is dependent. | App |-- Layout | |-- Navbar.tsx (Server Side) - Needs user and userData | |-- {children} -> page.tsx (Server Side) - Needs user to redirect if not logged and then passes it down as initial prop to a client component Here is a dependent code example:
js
const queryClient = new QueryClient();

const user = await queryClient.fetchQuery({
queryKey: ["user"],
queryFn: () => getUserServer(supabase),
});

if (!user) {
redirect(SIGN_IN);
}

if (user?.id) {
const cookieHeader = cookies().toString();
const userData = await queryClient.fetchQuery({
queryKey: ["userData", user?.id],
queryFn: () => fetchUserDataServer(cookieHeader, "translate page.tsx"),
});
}
js
const queryClient = new QueryClient();

const user = await queryClient.fetchQuery({
queryKey: ["user"],
queryFn: () => getUserServer(supabase),
});

if (!user) {
redirect(SIGN_IN);
}

if (user?.id) {
const cookieHeader = cookies().toString();
const userData = await queryClient.fetchQuery({
queryKey: ["userData", user?.id],
queryFn: () => fetchUserDataServer(cookieHeader, "translate page.tsx"),
});
}
Stack Overflow
Pass props to page.jsx child from root layout (next.js 13)
How do you pass props to the the page.jsx of layout? (NEXT 13) //app/blog/layout.jsx export default function RootLayout({ children }) { return ( <div> <Navbar /> <
0 Replies
No replies yetBe the first to reply to this messageJoin

Did you find this page helpful?