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