T
TanStack•9mo ago
eastern-cyan

Display Error when Error in context RouteOption?

In a createFileRoute() I have, I'm loading data from localstorage and putting the result in my route's context. How would I gracefully handle when the data in localstorage was corrupted and unparsable as JSON? Right now, my code throws a runtime error and my react app doesn't render. What I'd like to happen is the errorComponent be rendered.
xport const Route = createFileRoute("/$sessionId/_wizard")({
component: RouteComponent,
context: ({ params }) => {
const persistedContext = getPersistedData() // <-- this can throw an error

return {
myData: persistedContext,
};
},
onError: (e) => {
console.log(`bummer. got an error for this route`, e); // <-- this is never printed out
},
errorComponent: ErrorComponent // <-- this never renders
});
xport const Route = createFileRoute("/$sessionId/_wizard")({
component: RouteComponent,
context: ({ params }) => {
const persistedContext = getPersistedData() // <-- this can throw an error

return {
myData: persistedContext,
};
},
onError: (e) => {
console.log(`bummer. got an error for this route`, e); // <-- this is never printed out
},
errorComponent: ErrorComponent // <-- this never renders
});
I wonder if I'm doing something wrong here and should be using a different api. I guess the other option is to use React's built-in error boundaries, but I would think Tanstack router is nifty enough to have that taken care of for me. Yes, I'm a lazy coder 😉
2 Replies
other-emerald
other-emerald•9mo ago
does moving that call to beforeLoad work?
eastern-cyan
eastern-cyanOP•8mo ago
Yes, it did. Something I failed to see is that beforeLoad can set the context, too. Moving the code from context to beforeLoad solved the problem. That said, @Manuel Schiller , do you know what the purpose of the context function is? It seems like it is only for doing things that are pretty much guaranteed not to throw an error. It's useless if there's a chance an error can be thrown. The page isn't rendered and nothing is written to the console when an error occurs in context. weird.

Did you find this page helpful?