ln09nv2
ln09nv2

Reputation: 1343

How to get React Error Boundary to reset state with Try Again button?

My Pokemon application is using the following libraries: React Hook Form, React Query, and React Error Boundary.

When a request hasn't been made, it will should render No Pokemon Yet, Please Submit a Pokemon. When an error occurs, a Try Again button will render in place of No Pokemon Yet, Please Submit a Pokemon. When the Try Again button is clicked, No Pokemon Yet, Please Submit a Pokemon will again be shown and the search input is reset with the user again able to make a query.

However, my implementation is not working. Initially, No Pokemon Yet, Please Submit a Pokemon is not being rendered prior to the user submitting a query. Also, when I type a query that doesn't have any matches, the error boundary is not triggering to tell the user what has happened and allow them to resubmit a query after clicking the Try Again button. The DevTools Network tab gives me a 404.

React Error Boundary will only trigger if the img from PokemonInfo is uncommented. It renders Cannot read property 'front_default' of undefined.

Please let me know what I'm doing wrong.

Upvotes: 3

Views: 2223

Answers (1)

TkDodo
TkDodo

Reputation: 28843

I see two problems in your example:

  1. you are catching the error in the queryFn. react-query expects a failed promise to be returned in order to handle errors. If you catch it (just to log it as you're doing it), it will be a resolved Promise, hence no error. For logging errors, use the onError callback.

  2. in order to use error boundaries to handle errors, you need to set the property useErrorBoundary: true. This is best described on the suspense page in the docs, but you don't need to use it together with suspense: https://react-query.tanstack.com/guides/suspense

Upvotes: 3

Related Questions