import { TNewServicesProps } from '@/_constants/types';
import api from '@/_libs/api';
import { useMutation, useQueryClient } from '@tanstack/react-query';
const useManageServices = (
method: 'create' | 'update' | 'delete',
item_id?: number | string,
values?: TNewServicesProps
) => {
if ((method === 'update' || method === 'delete') && item_id == null) {
throw new Error(`item_id is required for ${method} method`);
}
const queryClient = useQueryClient();
const { data, error, isPending, mutateAsync, isSuccess } = useMutation({
mutationKey: [`${method}_services`],
mutationFn: async () => {
switch (method) {
case 'create':
return await api
.post(
`/admin/services/`,
JSON.stringify(values !== undefined ? values : {})
)
.then((res) => res.data)
.catch((error) => error.response.data);
case 'update':
return await api
.patch(
`/admin/services/${item_id}/`,
JSON.stringify(values !== undefined ? values : {})
)
.then((res) => res.data)
.catch((error) => error.response.data);
case 'delete':
return await api
.delete(`/admin/services/${item_id}/`)
.then((res) => res.data)
.catch((error) => error.response.data);
default:
throw new Error(`Invalid method: ${method}`);
}
},
//this is always fired, even when response code is 400, 500, etc.
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ['services'],
});
},
onError: () => {
//should do something but never fired
},
});
return { data, error, mutateStatus: mutateAsync, isPending, isSuccess };
};
export default useManageServices;
I'm currently experimenting with react-query in my project.
I'm facing an issue with error handling within my mutation.
When I check the network tab, I can see that the server responds with either a 400 or 500 status code, which I assumed would cause axios to throw an error, triggering the defined onError function.
However, the onSuccess function is always invoked.
What could I be overlooking? Thanks in advance.