Pass props globally
Answered
Samir posted this in #help-forum
SamirOP
I have a function to get user from supabase. I want to pass it in all pages.
app/layout.tsxconst getUser = async () => {
const supabase = createServerComponentClient({ cookies });
const { data } = await supabase.auth.getUser();
if (data.user) {
const userTable = await supabase
.from(SupabaseE.USER)
.select("*")
.eq("user_id", data.user.id);
return userTable.data?.[0] ?? null;
}
return null;
};
export default async function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
const user = await getUser();
return (
<html lang="en" suppressHydrationWarning>
<body className="flex flex-col items-center gap-3">
<ThemeProvider
attribute="class"
defaultTheme="dark"
enableSystem
disableTransitionOnChange
>
<Navbar user={user} />
{children}
</ThemeProvider>
</body>
</html>
);
}Answered by riský
in nextjs, it just caches for each request... so if you run the same function while rendering one request, its done only once, but if you reload the page, then if does it again
16 Replies
wrap the getUser in cache from react and then it will use the same result for each request (only cached for one render - next request it will do it again) and then run the cached request again as it should only be done once
SamirOP
ye
SamirOP
never used it
can u summarize it a bit
@Samir I have a function to get user from supabase. I want to pass it in all pages.
`app/layout.tsx`
ts
const getUser = async () => {
const supabase = createServerComponentClient({ cookies });
const { data } = await supabase.auth.getUser();
if (data.user) {
const userTable = await supabase
.from(SupabaseE.USER)
.select("*")
.eq("user_id", data.user.id);
return userTable.data?.[0] ?? null;
}
return null;
};
export default async function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
const user = await getUser();
return (
<html lang="en" suppressHydrationWarning>
<body className="flex flex-col items-center gap-3">
<ThemeProvider
attribute="class"
defaultTheme="dark"
enableSystem
disableTransitionOnChange
>
<Navbar user={user} />
{children}
</ThemeProvider>
</body>
</html>
);
}
SamirOP
I just have to wrap my getUser
in cache
right?
in nextjs, it just caches for each request... so if you run the same function while rendering one request, its done only once, but if you reload the page, then if does it again
Answer
if you put a quick console.log in function and run the getuser twice, you should only see the log once per request
and now you can import this function anywhere without worrying about if it is waist of requests
SamirOP
thank you so much!