React useQuery - useMutation onError not catching

Viewed 682

I'm using a combination of Axios and react-query to make a POST request to a server that may answer with response code 400 and validation errors.

export const axiosDefault = axios.create({
    baseURL: API_LINK,
    headers: {
        'Content-Type': 'application/json'
    },
})

const contactMutation = useMutation(
    (data) => axiosDefault.post('/contact', data),
    {
        onSuccess: (response) => {
            console.log('Success', response)
        },
        onError: (error) => {
           console.log('Error', error)
        }
    }
)

However, when calling contactMutation.mutate(someData) the error response from the server does not get processed by the react query library and instead propagates upward. Neither the onSuccess or onError handlers get called, the isError property of the mutation is also not set.

I've spent hours tearing my hair out over this, what am I doing wrong?

2 Answers

I literally have the same problem and I can't seem to find a solution. onError callback would simply not trigger and the state of the mutation is loading and stays like that forever.

hi i also had same issue i solved by wrapping api function to try/catch block and throw the catched Error.

(data) => {
    try {
       axiosDefault.post('/contact', data),
    } catch (error) {
       throw error
    }
 }

Related