T
TanStack2mo ago
deep-jade

Error handling with SSR and suspense queries on tanstack start

Hi, I'm using (for the first time, with no experience with this framework) Tanstack Start, paired with Tanstack Query. I followed the official example I found in tanstack start documentation to properly configure and use query in an SSR enviroment. When the queries correctly returns data there are no problems. However if the query fails (in my case, the rest API I'm calling can throw an error) while running on server I have an hydration error: A query that was dehydrated as pending ended up rejecting. It seems like the error is not properly handled with this SSR streaming setup. I've checked all the documentation but I'm not able to find a proper solution to this. This is my current code (not complete, only relevant parts): router.tsx
export function getRouter() {
const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 1000 * 60, // 60 seconds
retry: false,
},
},
});

const router = createRouter({
routeTree,
context: {
queryClient,
},
scrollRestoration: true,
defaultPreload: 'intent', // TODO: do we need this?
});

setupRouterSsrQueryIntegration({ router, queryClient });

return router;
}
export function getRouter() {
const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 1000 * 60, // 60 seconds
retry: false,
},
},
});

const router = createRouter({
routeTree,
context: {
queryClient,
},
scrollRestoration: true,
defaultPreload: 'intent', // TODO: do we need this?
});

setupRouterSsrQueryIntegration({ router, queryClient });

return router;
}
testComponent.tsx
export const Route = createFileRoute('/_authed/chats')({
component: RouteComponent,
loader: ({ context }) =>
context.queryClient.ensureQueryData(
findManyChatsQueryOptions({
sortBy: 'createdAt',
sortOrder: 'asc',
}),
),
});

function RouteComponent() {
const { data: chats } = useSuspenseQuery(
findManyChatsQueryOptions({
sortBy: 'createdAt',
sortOrder: 'asc',
}),
);

return (
<Container>
<Title>Chats</Title>
<List>
{chats.map((chat) => (
<List.Item key={chat.id}>
{chat.id} - {chat.type}
</List.Item>
))}
</List>
</Container>
);
}
export const Route = createFileRoute('/_authed/chats')({
component: RouteComponent,
loader: ({ context }) =>
context.queryClient.ensureQueryData(
findManyChatsQueryOptions({
sortBy: 'createdAt',
sortOrder: 'asc',
}),
),
});

function RouteComponent() {
const { data: chats } = useSuspenseQuery(
findManyChatsQueryOptions({
sortBy: 'createdAt',
sortOrder: 'asc',
}),
);

return (
<Container>
<Title>Chats</Title>
<List>
{chats.map((chat) => (
<List.Item key={chat.id}>
{chat.id} - {chat.type}
</List.Item>
))}
</List>
</Container>
);
}
1 Reply
ratty-blush
ratty-blush4w ago
Were you able to fix this? I am also running into this

Did you find this page helpful?