I am using useMutation to post data to my server, however, even when deliberately forcing error, my destructured isError is still false.
usecase: I am setting a loading spinner when isLoading is true, and spinner should stop when there’s an error.
`const axiosInstance = axios.create({
baseURL: “http://localhost:3000/api/”,
});
class APIClient<T> {
endpoint: string;
constructor(endpoint: string) {
this.endpoint = endpoint;
// Convert camelCase to snake_case for outgoing requests
axiosInstance.interceptors.request.use(
(config) => {
if (config.data && !(config.data instanceof FormData)) {
config.data = decamelizeKeys(config.data);
}
return config;
},
(error) => {
console.error("Error in request interceptor:", error);
return Promise.reject(error);
}
);
axiosInstance.interceptors.response.use(
(response) => {
if (response.data) {
response.data = camelizeKeys(response.data);
}
return response;
},
(error) => {
console.error("Error in response interceptor:", error);
return Promise.reject(error);
}
);
}
post = (body: T, config?: AxiosRequestConfig) => {
const headers = {
"X-CSRF-Token": this.getCSRFToken(),
"Content-Type":
body instanceof FormData ? "multipart/form-data" : "application/json",
};
return axiosInstance
.post<T>(this.endpoint, body, {
...config,
headers: { ...config?.headers, ...headers },
})
.then((res) => res.data);
};`
and my hook:
const useCreateStudio = () => { return useMutation({ mutationKey: ["studios"], mutationFn: (newStudio: Studio | FormData) => apiClient.post(newStudio), }); };
disclaimer: First time posting on Stackoverflow here, please let me know if this works, thanks!
I’ve tried directly throwing error in my interceptor
(error) => Promise.reject(error)
I’ve also tried logging the state but isError is always false.
I’ve removed .catch from my axios.post
tendermeat93 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.