T
TanStack3y ago
like-gold

Redirecting on log out

I'm having trouble getting my login page to render when calling the logout function provided by react-query-auth. It is changing the URL to /login, but not rendering the component specified by my login route. Leaving the screen and coming back, or refreshing forces the login component to render. I'm doing this via a guard like:
export default function AuthGuard({ children }: { children: React.ReactNode }) {
const { navigate } = useRouter();
const { user } = useAuth();

useEffect(() => {
if (!user?.id) {
// Redirect back to login if the user is no longer logged in
navigate({ to: loginRoute.fullPath });
}
}, [navigate, user?.id]);

return <>{children}</>;
}
export default function AuthGuard({ children }: { children: React.ReactNode }) {
const { navigate } = useRouter();
const { user } = useAuth();

useEffect(() => {
if (!user?.id) {
// Redirect back to login if the user is no longer logged in
navigate({ to: loginRoute.fullPath });
}
}, [navigate, user?.id]);

return <>{children}</>;
}
And my routes look like:
export const landingLayoutRoute = rootRoute.createRoute({
id: 'landing-layout',
component: () => (
<Landing>
<Outlet />
</Landing>
),
});

export const loginRoute = landingLayoutRoute.createRoute({
path: 'login',
component: () => <LoginPage />,
});

export const authenticatedLayoutRoute = rootRoute.createRoute({
id: 'authenticated-layout',
component: () => (
<AuthGuard>
<Header />
<Outlet />
</AuthGuard>
),
});

export const indexRoute = rootRoute.createRoute({
path: '/',
component: () => {
return (
<Main>
<Outlet />
</Main>
);
},
});

const routeConfig = rootRoute.addChildren([
indexRoute,
landingLayoutRoute.addChildren([
loginRoute,
]),
authenticatedLayoutRoute.addChildren([
homeRoute
]),
]);
export const landingLayoutRoute = rootRoute.createRoute({
id: 'landing-layout',
component: () => (
<Landing>
<Outlet />
</Landing>
),
});

export const loginRoute = landingLayoutRoute.createRoute({
path: 'login',
component: () => <LoginPage />,
});

export const authenticatedLayoutRoute = rootRoute.createRoute({
id: 'authenticated-layout',
component: () => (
<AuthGuard>
<Header />
<Outlet />
</AuthGuard>
),
});

export const indexRoute = rootRoute.createRoute({
path: '/',
component: () => {
return (
<Main>
<Outlet />
</Main>
);
},
});

const routeConfig = rootRoute.addChildren([
indexRoute,
landingLayoutRoute.addChildren([
loginRoute,
]),
authenticatedLayoutRoute.addChildren([
homeRoute
]),
]);
1 Reply
like-gold
like-goldOP3y ago
I have a temporary fix by using a <Link> component on my logout button, and waiting to call logout on my login page, if the user is defined on initial render. But I'm curious if there is a better way to handle this!

Did you find this page helpful?