I have issue with error response from axios client to my useMutation.
axios client
import axios from "axios";
const client = axios.create({ baseURL: `${process.env.REACT_APP_API_HOST}/${process.env.REACT_APP_API_PREFIX}` });
export const request = ({...options}) => {
client.defaults.headers.common.Authorization = `Bearer ${JSON.parse(localStorage.getItem('userDetails')).idToken}`
client.defaults.headers.common['Content-Type'] = 'application/json';
const onSuccess = (response) => {
console.log('AXIOS !!!!! request Successful!!!', response.config.url)
return response;
};
const onError = error => {
console.error('AXIOS !!!!! Request Failed:', error.config.url);
return error
};
return client(options).then(onSuccess).catch(onError);
}
this is my useMutatuon file
import { useMutation, useQueryClient } from 'react-query';
import {request} from '../utils/axios';
const useAddInvestmentAction = (investment) => {
// Define the headers object
return request({
url: '/investments/investment1',
method: 'post',
data: investment,
})
}
export const useAddInvestmentData = () => {
const queryClient = useQueryClient()
return useMutation(useAddInvestmentAction,{
onSuccess: () => {
queryClient.invalidateQueries('InvestmentsData')
console.log('Investment Added Successfully!!!!!!!!!!!!!!!!!')
},
onError: (error) => {
console.log('Investment Failed!!!!!!!!!!!!!!!!!')
console.log(error)
}
})
}
export default useAddInvestmentData;
when I change my url to not exist uri my onSuccess trigger and not my onError. The Axios print onError
any idea why?
2
Answers
In your
request
method you first catch the error and then you are returning the response of the error, not the error. Due to this the request is marked as successful. You will have to throw the error in order to forward the error.In
onError
you can throw a new ErrorAlso few suggestions:
useAddInvestmentAction
: This isn’t a hook. Just a method to add investment action. Just name it something like addInvestmentActionrequest
: This method waits for a response usingthen
. Better to make this method async.Better to use interceptors for implementing onSuccess and onError
You need to throw an error from the
catch
block. Also, remember that thecatch
block likethen
returns a promise unless an error is thrown.