Eb Heravi
Eb Heravi

Reputation: 398

Canceling my promises a POST Request through axios in Reactjs

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]);

Upvotes: 4

Views: 3892

Answers (4)

hackhan
hackhan

Reputation: 522

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();
}

Upvotes: -1

Amir Mehrabiani
Amir Mehrabiani

Reputation: 430

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();

Upvotes: 4

zahra banaeian
zahra banaeian

Reputation: 121

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

Upvotes: 2

mkareshky
mkareshky

Reputation: 212

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.');

Upvotes: 3

Related Questions