T
TanStack10mo ago
automatic-azure

Async Req for Context

Hey when setting up my app, I want to query the server to see if the user is logged in (redirect to login-in page if not) Is there a better way to do this than having the loading state?
export const App = () => {
const { data: user, isLoading } = useGetUserQuery();
if (isLoading) return <div>Loading...</div>;
return <RouterProvider router={router} context={{ user }} />;
};
export const App = () => {
const { data: user, isLoading } = useGetUserQuery();
if (isLoading) return <div>Loading...</div>;
return <RouterProvider router={router} context={{ user }} />;
};
4 Replies
stormy-gold
stormy-gold10mo ago
beforeLoad is a nice place for this case If you don't want to checkup on every route, you could group routes into (protected)/(public) routes and use beforeLoad in each of them and check like such
beforeLoad: ({ context }) => {
if (!context.user) {
throw redirect({
to: "/",
});
}
},
beforeLoad: ({ context }) => {
if (!context.user) {
throw redirect({
to: "/",
});
}
},
automatic-azure
automatic-azureOP10mo ago
Thanks, that'll work for what I need.
Is the recommended approach to show the loading state while fetching? I didn't see an async example in the docs.
stormy-gold
stormy-gold10mo ago
I would save the user in a session after authentication, that way getting the user from the context is constant and no need for loading states, just my opinion though
automatic-azure
automatic-azureOP10mo ago
Yeah, sounds like a good solution. Thanks for the help

Did you find this page helpful?