1

In React query every responses are considered as success.

Axios is used to call api request. Here is a axios component.

export const callAxios = async ({
    url,
    method,
    data,
    headers,
    params,
    responseType,
}: CallAxiosAPI) => {

    const config: AxiosRequestConfig = {
        method: method || 'GET',
        url: `${baseUrl}${url}`,
        headers: {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*',
            Authorization: accessToken !== null ? `Bearer ${accessToken}` : '',
            ...headers,
        },
        data,
        params,
        responseType,
    }
    return axios(config)
        .then((res: AxiosResponse<any, any>) => {
            return res
        })
        .catch(err => {
            return err
        })
}

Here is sample of using useMutation

const adjustProfit = useMutation(
        ['adjustProfit'],
        (params: { configurationId: string; configurationPriceId: number; data: IAdjustType }) => {
            return PricingQueries.adjustProfit(
                parseFloat(String(params.configurationId)),
                params.configurationPriceId,
                params.data,
            )
        },
        {
            onSuccess: () => {
                refetch()
            },
            onError: () => {
                toast.error(t(`message.adjust_price_failed`))
            },
        },
    )

Even there is error onSuccess is called.

1
  • 1
    axios will throw by default if response's status code is not 2xx. Remove the catch block and let react-query handle the thrown error. Notice that you are returning the error instead of re-throwing it. Commented Jan 11, 2023 at 4:55

1 Answer 1

2

The problem is the .catch. By catching an error because you want to log and then not re-throwing the error, you are transforming the error into a resolved Promise. So you're actually never returning the error to useQuery.

The fix is to remove the catch and use the onError callback for logging, or re-throw the error after logging.

This gotcha is so common that I have added it to my FAQ post: https://tkdodo.eu/blog/react-query-fa-qs#why-do-i-not-get-errors-

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.