chore: auth context

This commit is contained in:
Aslam H
2024-10-08 16:01:36 +07:00
parent 7c31f9b417
commit 94be662fc2
3 changed files with 8 additions and 10 deletions

View File

@@ -13,7 +13,7 @@ export function createRouter() {
defaultPreload: "intent", defaultPreload: "intent",
defaultErrorComponent: DefaultCatchBoundary, defaultErrorComponent: DefaultCatchBoundary,
defaultNotFoundComponent: () => <NotFound />, defaultNotFoundComponent: () => <NotFound />,
context: { queryClient }, context: { queryClient, auth: undefined! },
}), }),
queryClient, queryClient,
) )

View File

@@ -44,6 +44,7 @@ export const fetchClerkAuth = createServerFn("GET", async (_, ctx) => {
}) })
export const Route = createRootRouteWithContext<{ export const Route = createRootRouteWithContext<{
auth: { userId: string }
queryClient: QueryClient queryClient: QueryClient
}>()({ }>()({
meta: () => [ meta: () => [
@@ -77,15 +78,13 @@ export const Route = createRootRouteWithContext<{
{ rel: "manifest", href: "/site.webmanifest", color: "#fffff" }, { rel: "manifest", href: "/site.webmanifest", color: "#fffff" },
{ rel: "icon", href: "/favicon.ico" }, { rel: "icon", href: "/favicon.ico" },
], ],
beforeLoad: async ({ cause }) => { beforeLoad: async ({ context }) => {
if (cause !== "stay") { if (context.auth) {
const auth = await fetchClerkAuth() return { auth: context.auth }
return { auth }
} }
return { const auth = await fetchClerkAuth()
auth: null, return { auth }
}
}, },
errorComponent: (props) => { errorComponent: (props) => {
return ( return (

View File

@@ -1,8 +1,7 @@
import { createFileRoute, Outlet, redirect } from "@tanstack/react-router" import { createFileRoute, Outlet, redirect } from "@tanstack/react-router"
export const Route = createFileRoute("/_layout/_pages/_protected")({ export const Route = createFileRoute("/_layout/_pages/_protected")({
beforeLoad: ({ context, location, cause }) => { beforeLoad: async ({ context, location, cause }) => {
if (cause === "stay") return
if (!context?.auth?.userId) { if (!context?.auth?.userId) {
throw redirect({ throw redirect({
to: "/sign-in/$", to: "/sign-in/$",