How to handle 404 responses with TanStack useQuery?
Howdy folks. I am relatively new to React and trying to figure out how to update my queries to handle 404 errors. Should that be handled in the queryFn or using the onError function? I assumed that should be handled via the onError function, however when trying to provide proper type declaration to the parameter like in the screenshot, VS Code is telling me
No overload matches this call
Any advice is appreciated. Thanks a bunch!
3 Replies
fascinating-indigoOP•3y ago
i think i figured it out. i just needed to disable the error boundary in the query config.
foreign-sapphire•3y ago
Handling it in the
onError function should work. If the goal is to show an error message to the user, you can also handle that inside the queryFn and rethrow an error containing the error message to show to the user.
Also when using typescript, you don't necessarily need to pass types to useQuery, it can be automatically inferred from the return type of the queryFn function: https://tanstack.com/query/v4/docs/react/typescript#type-inferenceTypeScript | TanStack Query Docs
React Query is now written in TypeScript to make sure the library and your projects are type-safe!
Things to keep in mind:
fascinating-indigoOP•3y ago
so that i can handle the missing data in the component itself without it being throw up to the error boundary
thanks @julien !