I currently have a list of coordinates, which i use to fetch nearby hikes. Lets say I update my list state to new coordinates, but the fetch requests for the previous coordinates were not complete-- How can i cancel all the fetch requests made for the previous coordinates and only call new fetch requests based on the new coordinates?
I tried implementing AbortController
but its probably not working as it's not cancelling a "batch" of fetch requests, but only single fetch request. My code is below:
let abortController = new AbortController();
const getNearbyHikes = async (coordinates) => {
abortController.abort();
abortController = new AbortController();
for (const coord of coordinates) {
if (coord) {
try {
const { lat, lng } = cord.coordinates
const response = await fetch(
'http://localhost:5000/category/' + lat + "/" + lng + '/' + searchCategory,
{signal: abortController.signal}
)
const result = await response.json();
setHikes((prevState) => [...prevState, ...result.businesses])
} catch (error) {
if(error.name === 'AbortError'){
return;
}
throw error
}
}
}
}
Also , I want to update my UI with the hikes as I get them so it doesnt seem like my web app is really slow so I avoid using Promise.all
. Any suggestions or help is greatly appreciated.