Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React useQuery - useMutation onError not catching

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?

like image 355
Matúš Zeleňák Avatar asked Aug 10 '26 11:08

Matúš Zeleňák


1 Answers

Instead of using contactMutation.mutate(someData) use mutateAsync like contactMutation.mutateAsync(someData)

Source : https://github.com/TanStack/query/discussions/3575

like image 58
Teck_Geek Avatar answered Aug 12 '26 04:08

Teck_Geek