T
TanStack13mo ago
extended-salmon

Prevent `component` from rendering when `beforeLoad` throws an error.

This is my root router, and I want to prevent component from rendering its content when an error is thrown in beforeLoad. The docs says the following
This async function is called before a route is loaded. If an error is thrown here, the route's loader will not be called and the route will not render
https://tanstack.com/router/latest/docs/framework/react/api/router/RouteOptionsType#beforeload-method But in my case <Outlet /> is rendering although catch is logged in the console. Am I missing something?
export const Route = createRootRoute({
wrapInSuspense: true,
beforeLoad: async () => {
try {
await new Promise((resolve, reject) => setTimeout(reject, 1000));
} catch {
console.log('catch');
}
},
pendingComponent: () => <h1>Loading...</h1>,
component: () => <Outlet />,
});
export const Route = createRootRoute({
wrapInSuspense: true,
beforeLoad: async () => {
try {
await new Promise((resolve, reject) => setTimeout(reject, 1000));
} catch {
console.log('catch');
}
},
pendingComponent: () => <h1>Loading...</h1>,
component: () => <Outlet />,
});
RouteOptions type | TanStack Router React Docs
The RouteOptions type is used to describe the options that can be used when creating a route. RouteOptions properties
1 Reply
extended-salmon
extended-salmonOP13mo ago
I figured that I actually need to throw an error in the catch block
throw new Error()
throw new Error()

Did you find this page helpful?