We work with a terrible API where a 404 response means an empty array.
Is there a way to tell React Query to convert 404 error to an empty array?
I am hoping there is a way to do something like this?
const {data, isLoading, isError} = useQuery('key', apiCall, {
onError: (error) => {
if(error.statusCode === 404) {
setData([]);
setIsError(false);
}
}
});
react-query only cares about if your query function returns a resolved promise or a rejected promise. How you produce them is up to you. With that in mind, your query function can do more than just making an api call:
const {data, isLoading, isError} = useQuery(
'key',
async () => {
try {
return apiCall()
} catch (error) {
if(error.statusCode === 404) {
return []
}
throw error
}
}
);
this will catch all errors, transforms 404 errors into a resolved promise and thus an empty data array, and re-throws all other errors so that they wind up in the error field.
This is potentially a lot better than doing transformations in onError, because with onError, all retries have already happened, so you might get multiple, unnecessary requests. Also, there might be an in-between render cycle where the error is actually rendered on the screen (depends on react batching really).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With