T
TanStack•8mo ago
absent-sapphire

Navigating: Router Context always Undefined in beforeLoad

Hey all. I'm wondering what I misunderstood with router-context. What escapes me is that I have a _app folder which is my wrapper and in beforeLoad I check the context for an user object and I fetch it if not present in the context. But when I navigate between the pages the context is always undefined and the user info get's fetched every time. What am I missing here? Shouldn't the router context persist between the navigations?
4 Replies
rising-crimson
rising-crimson•8mo ago
how do you put the user onto the router context? ideally can you fork one of the existing router stackblitz examples to show the issue?
absent-sapphire
absent-sapphireOP•8mo ago
export const Route = createFileRoute('/_app')({
component: RootLayout,
beforeLoad: async ({ context }) => {
const validToken = checkTokenValidity();

if (!validToken) {
redirect({ to: '/login', throw: true });
}

const currentUser =
context.user ?? (await AccountManagmentService.getUserInfo());

return {
...context,
hubModules:
context.hubModules ?? (await HubModuleService.getHubModules()),
user: currentUser,
};
},
loader: ({ context }) => {
if (context.user?.pwInitialChange) {
redirect({ to: '/change-password', throw: true });
}
},
});
export const Route = createFileRoute('/_app')({
component: RootLayout,
beforeLoad: async ({ context }) => {
const validToken = checkTokenValidity();

if (!validToken) {
redirect({ to: '/login', throw: true });
}

const currentUser =
context.user ?? (await AccountManagmentService.getUserInfo());

return {
...context,
hubModules:
context.hubModules ?? (await HubModuleService.getHubModules()),
user: currentUser,
};
},
loader: ({ context }) => {
if (context.user?.pwInitialChange) {
redirect({ to: '/change-password', throw: true });
}
},
});
rising-crimson
rising-crimson•8mo ago
yeah context is not persisted it's constructed by the context you pass into router provider and all beforeload functions upon each navigation so if you want to cache it, you need to do it outside of the beforeload
absent-sapphire
absent-sapphireOP•8mo ago
Whoopsies. That blew right pass me 😄 No idea why I've thought that context is persisted. Dang it. Danke trotzdem 😉

Did you find this page helpful?