Axios cancellation problem for post method

Viewed 553

I'm building a Reactjs app using Axios to handle data request, the case is like this :

There is a form that will be filled by users, and when users click on the submit button to submit the form, there will be an Axios request to the API endpoint to submit the data, but during this request if users attempt to leave the page (either click on back button, redirect, or refresh the page), there will be an alert to warn users if the form data is submitting, but if users still want to leave the page,then the Axios request will be terminated (cancelled).

This is the outline of my code :

    const source = axios.CancelToken.source();
    axios.post(URL, data, {
        headers: {...},
        onUploadProgress: (progress) => {....},
        cancelToken: source.token,
    })
    .then((res) => {
        console.log('form submitted')
    })
    .catch((thrown) => {
        if(axios.isCancel(thrown)){
            console.log('cancelled')
        } else {
            // error handling
        }
    })

    window.onpopstate = () => {
        if(window.confirm('Are You Sure to.....') {
            source.cancel();
        }
    }

And the problem is when window.confirm returns true and the cancel method is run, the cancelled message is printed in the console which I consider it as a success cancellation, but when I open up my database, I find out that the data that just has been cancelled is already in there and what I want is the data not to be stored because the request is already cancelled. Note that the form submitted message is never shown. I know that Axios is async but I'm pretty sure that the cancellation is actually successful like I said before.

0 Answers
Related