T
TanStack2y ago
xenial-black

[SOLVED] beforeLoad wait for auth?

I'm using the root route with context and storing my auth in there. I'm running a validateAuth function in the beforeLoad of my protected routes. But it appears that the beforeLoad occurs faster and before my auth concludes that the user is still logged in. Is there any way to wait for the auth check to occur? I'm having a hard time figure this out, and this results in being immediately redirected to login after refreshing the page on a protected route.
1 Reply
xenial-black
xenial-blackOP2y ago
Here's my app
function App() {
const { data: auth, isLoading, isValidating } = useAuth()

if (!isValidating && !auth && isLoading) {
return <DefaultLoader />
}

return <RouterProvider router={router} context={{ auth }} />
}
function App() {
const { data: auth, isLoading, isValidating } = useAuth()

if (!isValidating && !auth && isLoading) {
return <DefaultLoader />
}

return <RouterProvider router={router} context={{ auth }} />
}
Here's my validateAuth
export function validateAuth({
context,
location,
}: {
context: RouterContext
location: ParsedLocation
}) {
if (!context.auth) {
toast.info('Please login to continue', {
id: 'login-to-continue',
})
throw redirect({
to: '/login',
search: {
redirect: location.href,
},
})
}
export function validateAuth({
context,
location,
}: {
context: RouterContext
location: ParsedLocation
}) {
if (!context.auth) {
toast.info('Please login to continue', {
id: 'login-to-continue',
})
throw redirect({
to: '/login',
search: {
redirect: location.href,
},
})
}
Similar issue https://discord.com/channels/719702312431386674/1202498120387399731 I think it might be simply how I've done my App component. Maybe I need to change out the condition for when a loader should be shown. Cause I believe the beforeLoad runs after RouterProvider is rendered. This was my answer
function App() {
const { data: auth, error, isLoading, isValidating } = useAuth()

if ((!auth && !error) || (isLoading && !isValidating)) {
return <DefaultLoader />
}

return <RouterProvider router={router} context={{ auth }} />
}
function App() {
const { data: auth, error, isLoading, isValidating } = useAuth()

if ((!auth && !error) || (isLoading && !isValidating)) {
return <DefaultLoader />
}

return <RouterProvider router={router} context={{ auth }} />
}

Did you find this page helpful?