T
TanStack15mo ago
jolly-crimson

Handle 404 from a component query

I am using '@tanstack/react-query' and '@tanstack/react-router'. I have a component that is a child in my __root.tsx that queries the api. When it works, it works, but I am having trouble in the context of this file based router to figure out what to do when it 404s. This one data fetch in turn runs the entire ui and every query afterwards, so the ui won't work if that one request fails. Ideally I'd like to just display an error component, or reroute to one in the
if (isError) {...}
if (isError) {...}
section of that component, but I don't know what would be proper protocol here. I had
if (isError) {
return (
<CatchBoundary getResetKey={() => 'reset'} onCatch={(error) => console.error(error)}>
<div>Error fetching dates..</div>
</CatchBoundary>
)
}
if (isError) {
return (
<CatchBoundary getResetKey={() => 'reset'} onCatch={(error) => console.error(error)}>
<div>Error fetching dates..</div>
</CatchBoundary>
)
}
like in the documentation, but obviously the rest of the ui still renders in addition to this now ^
3 Replies
itchy-amethyst
itchy-amethyst15mo ago
why do you fetch in the component? if you fetch in the loader, you could throw a notFound
jolly-crimson
jolly-crimsonOP15mo ago
to be honest I don't really know. The app is a dashboard, with a bunch of different components. All with separate data, but multiple components per page(route). So from that standpoint I didn't think it was really possible I'm fairly new to react-query (1 year), but I've only been experimenting with tanstack/react-router for the last couple weeks I'd like to learn the proper way though if you have any recommendations to further explain the situation. here is the __root.tsx
function RootComponent() {
const [scroll, scrollTo] = useWindowScroll()

return (
<AppShell header={{ height: 80, offset: true }} footer={{ height: 16 }}>
<AppShellHeader withBorder={false} bg="transparent">
<Container size="xxl">
<Navigation />
</Container>
</AppShellHeader>
<AppShellMain>
function RootComponent() {
const [scroll, scrollTo] = useWindowScroll()

return (
<AppShell header={{ height: 80, offset: true }} footer={{ height: 16 }}>
<AppShellHeader withBorder={false} bg="transparent">
<Container size="xxl">
<Navigation />
</Container>
</AppShellHeader>
<AppShellMain>
and in the navigation (app bar) there is a date picker component that is populated with available dates from the api. so not really a route
itchy-amethyst
itchy-amethyst15mo ago
I would use something like this:
export const Route = createRootRoute({
component: RootComponent,
loader: async () => {
try {
await queryClient.ensureQueryData(PUT_YOUR_QUERY_KEY_HERE)
} catch(e) {
throw notFound()
}
})
export const Route = createRootRoute({
component: RootComponent,
loader: async () => {
try {
await queryClient.ensureQueryData(PUT_YOUR_QUERY_KEY_HERE)
} catch(e) {
throw notFound()
}
})

Did you find this page helpful?