4

I used to post requests for getting data because I want to fetch data from the server by sending some filters.

How can I do Cancel my promises Fetch data through the onClick button in Reactjs?

Is it correct to use the HTTP post method, to select data when we have several parameters to filter the data?


I find the address but it's not work:

   const CancelToken = axios.CancelToken;
   let cancel;
   function handleProductSearch() {
   var newModel=searchProductFilter;
    const token = localStorage.token;
    if (token) {
     
  // Cancel previous request
        if (cancel !== undefined) {
            cancel();
            setLoadingListResSrch(false)

        }
        axios.post(baseUrl + 'Basic/ProductSearch', newModel, {
            cancelToken: new CancelToken(function executor(c) {
               cancel = c;
            }),
            headers: {
                'Content-Type': 'application/json',
                Accept: 'application/json',
                'Authorization': `Bearer ${token}`
            },
            credentials: 'same-origin',
        }) .then(response => {
                setLoadingListResSrch(false)
                if (response.data.length === 0) {
                    setGoodListResSrch(response.data.result);
                }
            }) .catch(error => {
                setLoadingListResSrch(false)
                debugger;
                if (axios.isCancel(error)) {
                    console.log("post Request canceled");
                    return;
                }  return;
            }); 
         }
      }

and I want when the user click in the new button previous request is canceled.

 <FormGroup className="mb-2 ml-sm-2 mb-sm-2">
     <div color="seccess" size="sm" className="btn btn-info m-3"
      onClick={handleAbrotProductSearch}>
         new search</div>
 </FormGroup>
   const handleAbrotProductSearch = useCallback(() => {
     handleProductSearch());
}, [handleProductSearch]);
Eb Heravi
  • 398
  • 5
  • 15
  • Does this answer your question? [How do I cancel an HTTP fetch() request?](https://stackoverflow.com/questions/31061838/how-do-i-cancel-an-http-fetch-request) – smashed-potatoes Aug 15 '20 at 05:16
  • it is OK , but I want to used in HTTP post method ,and AbortController not work in fetching type post – Eb Heravi Aug 15 '20 at 05:24

4 Answers4

4

You can both cancel and abort.

I have given examples of both cases.

for cancel:

const CancelToken = axios.CancelToken;
let cancelPost;
axios.post('/MyReallySlowReport', {
  name: 'new name'
}, {
  cancelToken: new CancelToken(function executor(c) { 
    cancelPost = c;
  })
})

// cancel the request
cancelPost();

//back end mvc c# example
public async Task<ActionResult> MyReallySlowReport(CancellationToken cancellationToken)
{
     CancellationToken disconnectedToken = Response.ClientDisconnectedToken;            
     var source = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, disconnectedToken);

    List<ReportItem> items;
    using (ApplicationDbContext context = new ApplicationDbContext())
    { 
        items = await context.ReportItems.ToListAsync(source.Token);
    }
    return View(items);
}

And for Abort:

var xhr = $.ajax({
  method: "POST",
  url: "/MyReallySlowReport",
  data: { name: "John", location: "Boston" }
})
  .done(function( msg ) {
    alert( "Data Saved: " + msg );
  });

// abort the request
xhr.abort();
Amir Mehrabiani
  • 422
  • 3
  • 8
3

If you use axios this can be done by using a cancel token:

axios.isCancel(thrown)

https://blog.logrocket.com/how-to-make-http-requests-like-a-pro-with-axios/

const source = axios.CancelToken.source();

axios.get('https://media.giphy.com/media/C6JQPEUsZUyVq/giphy.gif', {
  cancelToken: source.token
}).catch(thrown => {
  if (axios.isCancel(thrown)) {
    console.log(thrown.message);
  } else {
    // handle error
  }
});

// cancel the request (the message parameter is optional)
source.cancel('Request canceled.');
mkareshky
  • 202
  • 3
  • 7
2

It's true to use HTTP post method because you are sending filters by using body.

zahra banaeian
  • 121
  • 1
  • 6
-1

Yes, it's alright to send filters with POST, and to cancel a fetch request you just have to use an AbortController object if you're using the Fetch API.

const controller = new AbortController();
fetch(url, { signal: controller.signal })
  .then(response => {
    console.log(`Complete!`);
  }).catch(e => {
    console.error(`Error!: ${e.message}`);
  });


// call abort to cancel the fetch request
const cancelRequest = () => {
  controller.abort();
}
hackhan
  • 512
  • 3
  • 7
  • 1
    AbortController is also usable in axios, I don't see why answer with a different method when the question specifically states it want's an `axios` solution. – Silidrone Sep 09 '22 at 16:59
  • CancelToken is deprecated though – gerl Mar 28 '23 at 21:57