Reputation: 768
I'm trying to use react-query mutations using axios but when my request return an http error my catch()
is not being called.
This is what i tried:
const BannerRightConfirmEmail = () => {
const [{ token }] = useState<ITokenConfirmationEmailParam>(useParams());
const [mutateConfirmEmail] = useMutation(confirmEmailUser);
useEffect(() => {
confirmEmail();
}, []);
const confirmEmail = async () => {
try {
await mutateConfirmEmail(token);
} catch (errorReq) {
console.log(errorReq);
}
};
my user.service.ts:
const confirmEmailUser = async (token: string) => {
await api.patch('/users/confirmEmail/' + token)
}
export { confirmEmailUser }
my api.ts:
const api = axios.create({
baseURL: "http://localhost:3100",
});
My request is returning a 400 error status, but nothing is being printed in my catch()
, why?
Upvotes: 5
Views: 13342
Reputation: 368
The mutate function handles the exception so the catch block will never run. You can handle errors using the onError
handler function that can be set on the hook or mutate function level. For instance:
const [
mutate,
{ status, isIdle, isLoading, isSuccess, isError, data, error, reset },
] = useMutation(mutationFn, {
onError(err, variables, onMutateValue) {
// error handling logic
// fires after the mutate-level handler
}
})
const promise = mutate(variables, {
onError(err, variables, onMutateValue) {
// error handling logic
// fires before the hook-level handler
}
})
As an alternative you can also move the error handling logic inside the mutationFn
passed to useMutation
like this:
const confirmEmailUser = async (token: string) => {
let response;
try {
response = await api.patch('/users/confirmEmail/' + token)
} catch (errorReq) {
console.log(errorReq);
}
return response;
}
export { confirmEmailUser }
This way you can handle the error before it reaches react-query
Upvotes: 5