Although this question has been asked many times, it still doesn't work in my case. I followed the answer from @Drew Reese at How to integrate AbortController with Axios and React? but the abort() does not seem to work. My code looks like this.
I first create an exported Axios
(latest version) instance.
const axiosInstance = axios.create({
baseURL: API,
headers: {
Accept: 'application/json',
},
});
axiosInstance.interceptors.request.use((config) => {
config.formSerializer = { indexes: null };
return config;
});
export default axiosInstance;
Inside my react component I do this.
import axios from '../mycomponents';
const abortControllerRef = useRef(new AbortController());
...
...
const onSubmit = handleSubmit(async (mydata) => {
...
...
try {
axios.defaults.headers['Content-Type'] = 'multipart/form-data';
const res = await axios({
method: 'post'
url,
data: mydata,
onUploadProgress : handleProgress,
signal: abortControllerRef.current.signal,
});
} catch (err) {
if (err.name === 'CanceledError') {
console.error('Operation canceled');
// reset controller
abortControllerRef.current = new AbortController();
else
console.error(err);
}
}
.....
.....
const cancelUpload = () => {
const controller = abortControllerRef.current;
controller.abort();
};
the cancelUpload
is called from a button callback but it never aborts a list of uploading files (multiple files were selected).
EDIT after @AkeelAhmedQureshi suggestion
After @AkeelAhmedQureshi suggestion I fixed the signal
typo error. Now, I can catch the error and report the cancelation upload, BUT Axios continues the posting and finally, after some seconds, the server receives most of the payload (ie 2 out of 5 files and the rest of the data) as normal. The server completes the transaction even with some of the files originally selected. Where am I wrong here?
Here is what my browser reports.