Best way to handle errors with multiple components sharing queries
I have encountered a use case and would like to know the best practice for handling it. I have three components that use the same hook, retrieving “requests.”
In case of failure, I want to display an ErrorRequest.tsx component, which may be the same or different in each component, that doesn't matter. The problem is that if I check the “isError” state in each component, I will end up displaying the ErrorRequest.tsx component three times when there is an error, which would be strange for the user. Also, if I want to pass the refetch function, the buttons in ErrorRequest.tsx will not be synchronized because they do not share state.
I discussed this with Claude, and he said that the only solution would be for a single component to request isError and return ErrorRequest.tsx, and for the other two to return an empty fragment. But I don't think that solution is scalable. Another option would be an ErrorBoundary, but I have other components that use other hooks on the page, and it would be bad for the user if, because one endpoint has an error, they couldn't see other components that don't have it.
What is the best approach for this?

5 Replies
ambitious-aqua•2w ago
I don't think there's 1 good way to handle this, it depends on the UX & UI you want. but my first question: are each of these components rendered at the same time, and are they each doing
useRequest
on the same API endpoint?useful-bronzeOP•2w ago
Yes, that's the main problem. The 3 are rendered on the same page and at the same time, and use the same hook.
sunny-green•2w ago
You could use the global callbacks and meta for this type of error. Maybe use a context tree to scope to only part of the tree?
https://tkdodo.eu/blog/react-query-error-handling this is as always a good resource
React Query Error Handling
After covering the sunshine cases of data fetching, it's time to look at situations where things don't go as planned and "Something went wrong..."
useful-bronzeOP•2w ago
I'm reviving this thread 😓. The problem with wrapping components in ErrorBoundary is that it would make them very dependent on where they are located in the app. So if I want to reuse them elsewhere, it would be somewhat problematic, since I would have to take this specific error handling into account. Basically, it would end up being the same as having an isError ? return null in some components. What I want is for it not to be so situational.
sunny-green•2w ago
React Query Error Handling
After covering the sunshine cases of data fetching, it's time to look at situations where things don't go as planned and "Something went wrong..."