T
TanStack3mo ago
adverse-sapphire

component render running before "beforeLoad"

root.tsx
export const Route = createRootRouteWithContext<{
auth: {
session: Session;
user: UserWithAnonymous;
} | null;
}>()({
beforeLoad: async () => {
const { data } = await authClient.getSession();
return { auth: data };
},
loader: ({ context }) => {
return { user: context.auth?.user };
},
component: () => (
<RootDocument>
<Outlet />
<TanStackRouterDevtools position="bottom-right" />
</RootDocument>
),
});

function RootDocument({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<head>
<HeadContent />
</head>
<body className="bg-secondary">
<AuthLayer>{children}</AuthLayer>
<Scripts />
</body>
</html>
);
}
export const Route = createRootRouteWithContext<{
auth: {
session: Session;
user: UserWithAnonymous;
} | null;
}>()({
beforeLoad: async () => {
const { data } = await authClient.getSession();
return { auth: data };
},
loader: ({ context }) => {
return { user: context.auth?.user };
},
component: () => (
<RootDocument>
<Outlet />
<TanStackRouterDevtools position="bottom-right" />
</RootDocument>
),
});

function RootDocument({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<head>
<HeadContent />
</head>
<body className="bg-secondary">
<AuthLayer>{children}</AuthLayer>
<Scripts />
</body>
</html>
);
}
auth-layer.tsx ```tsx import { authClient } from "@/lib/auth/client"; import { getRouteApi, useRouter } from "@tanstack/react-router"; import { Loader } from "lucide-react"; import type React from "react"; import { useEffect } from "react"; export default function AuthLayer({ children, }: { children: React.ReactNode; }) { const routeApi = getRouteApi("
root__"); const { user } = routeApi.useLoaderData(); const router = useRouter(); useEffect(() => { if (!user || !user.isAnonymous) { (async () => { await authClient.signIn.anonymous(); await router.invalidate(); })(); } }, [user]); if (user) { return <>{children}</>; } return ( <div className="flex min-h-screen items-center justify-center"> <Loader className="size-4 animate-spin" /> </div> ); } ``` the anonymous signin call is being made before getSession
2 Replies
foreign-sapphire
foreign-sapphire3mo ago
please provide a complete minimal example by forking one of the existing router examples on stackblitz
adverse-sapphire
adverse-sapphireOP3mo ago
okay

Did you find this page helpful?