Stack Overflow Asked by Eb Heravi on February 11, 2021
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]);
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();
}
Answered by hackhan on February 11, 2021
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();
Answered by Amir Mehrabiani on February 11, 2021
It's true to use HTTP post method because you are sending filters by using body.
Answered by zahra banaeian on February 11, 2021
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.');
Answered by mkareshky on February 11, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP