How to control the error when return undefined from a fetch?
I am getting this console error: Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ["Jockey"].
I am fetching without turn on the backend and I want to know how to control that error.
5 Replies
passive-yellow•3y ago
I don't think you want the
await before response.json, just before fetch?
But the docs do say, "Must return a promise that will either resolve data or throw an error. The data cannot be undefined." (https://tanstack.com/query/v4/docs/react/reference/useQuery)
Anyway, I don't use try/catch blocks for my query functions.absent-sapphireOP•3y ago
@ƘЄѴɬƝ perfect. The code is gonna be?
Is necessary
if (!response.ok)?like-gold•3y ago
this is the problem in the original code:
this catches the error, but doesn't re-throw it. Since your function is async, and a promise must be returned, this implicitly returns a
Promise with undefined data, basically being equivalent to:
and that's why undefined shows up in your query cache, and that is not allowed. This gotcha is so common that I have added it to my FAQ blog post: https://tkdodo.eu/blog/react-query-fa-qs#loggingReact Query FAQs
Answering the most frequently asked React Query questions
absent-sapphireOP•3y ago
@TkDodo 🔮 good to know. Actually, I am learning and implement tanstack to the project, so, I have to refactor.
my final code so will be:
@TkDodo 🔮 @ƘЄѴɬƝ thanks for your help
like-gold•3y ago
please also see: https://tkdodo.eu/blog/react-query-fa-qs#the-fetch-api
React Query FAQs
Answering the most frequently asked React Query questions