T
TanStack2y ago
xenophobic-harlequin

Redirect when isAuthenticated value in context is changing

I keep my auth user in redux. I'm doing something like this;
// Create a new router instance
const router = createRouter({
routeTree,
notFoundRoute,
defaultPreload: 'intent',
defaultPendingComponent: LoadingPlaceholder,
context: {
isAuthenticated: false,
},
});


export function RouterProvider({ router }: { router: RouterProps['router'] }) {
const { isAuthenticated } = useAuth();
return (
<TanstackRouterProvider
router={router}
context={{ isAuthenticated }}
basepath={__PUBLIC_URL__}
/>
);
}

//_app layout

export const Route = createFileRoute('/_app')({
component: AppLayout,
beforeLoad: async ({ context, location }) => {
if (!context.isAuthenticated) {
throw redirect({
to: '/login',
search: {
redirect: location.href,
},
});
}
},
});
// Create a new router instance
const router = createRouter({
routeTree,
notFoundRoute,
defaultPreload: 'intent',
defaultPendingComponent: LoadingPlaceholder,
context: {
isAuthenticated: false,
},
});


export function RouterProvider({ router }: { router: RouterProps['router'] }) {
const { isAuthenticated } = useAuth();
return (
<TanstackRouterProvider
router={router}
context={{ isAuthenticated }}
basepath={__PUBLIC_URL__}
/>
);
}

//_app layout

export const Route = createFileRoute('/_app')({
component: AppLayout,
beforeLoad: async ({ context, location }) => {
if (!context.isAuthenticated) {
throw redirect({
to: '/login',
search: {
redirect: location.href,
},
});
}
},
});
When i'm reseting the state (logout) in redux isAuthenticated change, but the router doesn't redirect me. I have to navigate manually to the /login route.
2 Replies
foreign-sapphire
foreign-sapphire2y ago
Have you considered using router.invalidate() after Redux has emptied the auth state? It'd trigger a re-render upon which it'd catch the fact that the user isn't authed anymore. All that being said, if you could also just abstract away that navigate logic into a useLogout hook as well. Just a matter of what behavior you want for your app.
xenophobic-harlequin
xenophobic-harlequinOP2y ago
I tried using router.invalidate() but i need to press the logout button twice to send me to the /login page. Maybe i will have to force a navigate when i sign out from the app. Also i have an axios interceptor to sign out the user when i receive 401 response. So i have to import the router and call also manually navigate to login page.

Did you find this page helpful?