The solution depends on what you were putting into those callbacks. A few examples:
Global error handling
If you want default error handling that applies to all of your queries, you should set that up just once when creating your query client. For example:
const queryClient = new QueryClient({
queryCache: new QueryCache({
onError: (error) => {
console.error('Uh oh', error.message);
}
}),
})
If you want to modify this for individual queries, you can use the meta option to provide data on how to handle the error. For example, if you want each query to provide its own custom error message:
const queryClient = new QueryClient({
queryCache: new QueryCache({
onError: (error, meta) => {
toast(meta.errorMessage);
}
}),
})
// elsewhere:
useQuery({
queryKey: ['items'],
queryFn: fetchItems,
meta: {
errorMessage: 'Failed to fetch items',
},
})
Using error for rendering
If you were using the onError to set some local state, which then gets used in the render calculation, instead use the values returned by useQuery itself to drive that ui. For example:
const { data, isError } = useQuery({
queryKey: ['items'],
queryFn: fetchItems,
});
if (isError) {
return <div>Uh oh, something went wrong</div>
}
// ...
Error side effects
If you're doing some side effect (eg, logging, showing a toast, navigating to a different page), put that into a useEffect.
const { data, isError } = useQuery({
queryKey: ['items'],
queryFn: fetchItems,
});
useEffect(() => {
if (isError) {
console.error('Uh oh')
navigate(-1);
}
}, [isError]);
Request level error handling
Sometimes you'll have error handling which is closely related to the specific request. Like maybe you want to normalize error codes, or replace a 404 with a success that returns null. This sort of handling it typically best put in the query function (myFunctionThatReturnsPromise in your example)
const myFunctionThatReturnsPromise = async () => {
try {
return await axios.get(/* ... */);
} catch (error) {
if (error.response.status === 404) {
return null;
} else {
throw error;
}
}
}
If you have any specific cases that you don't think fit with these categories, please feel free to mention them in the comments.