I am trying to implement a simple functionality in react, which, if the fetch request is not completed, and meanwhile another fetch request made, previous fetch request will be cancelled, and new one will be called. I have implemented the same functionality in useEffect hook for some another component, and it worked great. This time I directly using react functions to implement the same, everything seems working fine, except that fetch request result is still getting displayed, even when Abort() is called on the signal as you can see in the code below.
let submitDebouncer;
let submitAborter = null;
function sleep(ms){
return new Promise(resolve => setTimeout(resolve, ms))
}
async function fetcher(url){
if(submitAborter){
console.log(submitAborter);
submitAborter.abort();
console.log(submitAborter);
}
submitAborter = new AbortController();
const runSignal = submitAborter.signal;
try{
const response = await fetch(url, {runSignal});
const data = await response.json();
submitAborter = null;
setDisplayData(data);
console.log(data);
} catch(e){
console.log(e.name)
}
}
function handleSubmit(){
if(submitDebouncer){
clearTimeout(submitDebouncer);
}
setLoading(true)
submitDebouncer = setTimeout(() => {
const url = `http://api.openweathermap.org/geo/1.0/direct?q=${city}&limit=1&appid=${API_Key}`;
fetcher(url)
sleep(50)
fetcher(url)
}, 200)
}
Here is a screenshot of the ouput Output of the above script
In it, the aborted state is set to true, therefore abort() is getting called but output is still revieved. Any help is greatly appreciated
I was expecting the fetch request to be aborted, and the redundant result not to get displayed. Although the abort() is called, and redundant result (which should be aborted) is also displayed.
You need to set the signal property, not runSignal. So you need to do:
const response = await fetch(url, {signal: submitAborter.signal});