Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-query useMutation onError never firing

I'm currently trying out react-query in my project.

I'm having trouble with handling errors within my mutation.

In my networks tab, I can confirm that the server is responding with code 400 or 500, which I assumed makes axios throw an error, thus firing the defined onError function.

However, the onSuccess function is always called no matter how the API call goes.

What am I missing here? Thanks in advance.

const { mutate } = useMutation(
['mutation'],
() => axios.patch(API_URL, params),
{
  onSuccess: () => {
    //this is always fired, even when response code is 400, 500, etc.
    void queryClient.invalidateQueries('query');
  },
  onError: () => {
    //should do something but never fired
  },
}

);

like image 221
mymoto Avatar asked Feb 15 '26 02:02

mymoto


1 Answers

Make sure to return the result of your mutation function (i.e. the axios.patch call needs to be returned)

const { mutate } = useMutation(['mutation'], () => return axios.patch(API_URL, params),
{
  onSuccess: () => {
    //this is always fired, even when response code is 400, 500, etc.
    void queryClient.invalidateQueries('query');
  },
  onError: () => {
    //should do something but never fired
  },
})
like image 55
Josh Avatar answered Feb 17 '26 16:02

Josh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!