T
TanStack2y ago
metropolitan-bronze

Infer context types in authenticated routes

Hi. I am using this example from tanstack router https://tanstack.com/router/latest/docs/framework/react/examples/authenticated-routes-context I'd like to change context type so the user in authenticated routes is not possibly undefined. In this example its dashboard.tsx Since we check user before load I'd like to overwrite user type. How can I do it?
React Router Authenticated Routes Context Example | TanStack Router...
An example showing how to implement Authenticated Routes Context in React Router
2 Replies
metropolitan-bronze
metropolitan-bronze2y ago
You could return the user in the beforeLoad callback once its been validated.
export const Route = createFileRoute('/dashboard')({
beforeLoad: ({ context, location }) => {
const user = context.auth.user;
if (!user) {
throw redirect({
to: '/login',
search: {
redirect: location.href,
},
})
}
return { user }
},
loader: ({ context }) => {
const user = context.user
},
component: DashboardComponent,
})
export const Route = createFileRoute('/dashboard')({
beforeLoad: ({ context, location }) => {
const user = context.auth.user;
if (!user) {
throw redirect({
to: '/login',
search: {
redirect: location.href,
},
})
}
return { user }
},
loader: ({ context }) => {
const user = context.user
},
component: DashboardComponent,
})
metropolitan-bronze
metropolitan-bronzeOP2y ago
Thats super cool Thank you @Sean Cassiere

Did you find this page helpful?