In the react query v3 or less there are onSuccess onError callbacks, i used them a lot and i find them important.
const {data, isLoading} = useQuery("my_key", myFunctionThatReturnsPromise, {
// other settings,
onSuccess: (data) => // do something on success,
onError: (data) => // do something on error,
})
There isn't onSuccess and onError in the new tenstack query.... How do i handle errors? Do i simply just write my own async try catch function insead of just myFunctionThatReturnsPromise.
How can i use onSuccess and onError in tenstack query :( ?
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:
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: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:
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.
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)If you have any specific cases that you don't think fit with these categories, please feel free to mention them in the comments.