Repository navigation
Confusing useRouteContext behavior within an errorComponent
#6258
Replies: 1 comment
|
This was a bug, not a misuse. I reproduced it on It's fixed in
So upgrading fixes it. If you can't upgrade yet, read the context from the ancestor that produced it. That ancestor's match succeeded, so its context is complete even on the affected versions: import { useRouteContext } from '@tanstack/react-router'
function MyErrorComponent({ error }: ErrorComponentProps) {
const { user } = useRouteContext({ from: '__root__' })
// or: Route.useRouteContext() on the root route object
return <ErrorPage user={user} error={error} />
}This is also a good habit in general for data that "belongs" to a parent. With |
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
I'm trying to understand the expected behavior of
useRouteContextwithin anerrorComponent.I'm loading current user information in my
__rootroute'sbeforeLoad, and I'd like to display some of that user information in error components throughout my application.When a descendant route's
beforeLoadthrows an error, theerrorComponentfor that route can calluseRouteContext(), but some of the parent context properties are undefined, even though the parent'sbeforeLoadcompleted successfully. Interestingly, context provided via the React<RouterProvider context={...}>is accessible.Here's an example StackBlitz to demonstrate what I'm talking about: https://stackblitz.com/edit/github-4kchyyu8?file=src%2Froutes%2Findex.tsx (note also that when a module is hot replaced on edit, both the
RouterProvidercontext property and the__rootcontext property are available, but I'm less interested in digging into this because that's not something that will happen in production).Questions:
I'm guessing that using
useRouteContextinerrorComponentdoesn't make sense and this is just user error (at least, the types seem to suggest this). Regardless, I'd appreciate any guidance on the expected behavior and best practices!All reactions