React useQuery - useMutation onError not catching
Asked Answered
A

2

7

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?

Anatolian answered 2/5, 2022 at 19:34 Comment(1)
code looks correct on first sight. Can you show a codesandbox reproduction with the issue?Clear
A
2

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
    }
 }

Adolpho answered 15/6, 2022 at 17:25 Comment(1)
this fixed my issue also, but why is this necessary?Sypher
Z
1

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

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

Zeldazelde answered 27/4, 2023 at 11:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.