I have a React app that can makes a series of fetch requests, depending on user interactions. I want to abort old fetch requests any time the app receives a new one.
To accomplish this, I've created a custom hook, useData. Its main fucntion is running a useEffect hook whenever the url changes. The easiest way to abort old requests seems to me to be using the cleanup mechanism provided by useEffect. But this will call abort on all requests, not just incomplete ones.
Are there any hidden problems this might cause? It seems that it shouldn't do much to a resolved fetch, but I can't find any documentation to support that.
This is my code:
/** Returns data for a given url. */
export const useData = function (dataUrl) {
const [loadedData, setLoadedData] = useState(Object.assign({}));
// runs if/when the url changes
useEffect(() => {
// new controller for each new url
const controller = new AbortController();
async function getData(dataUrl) {
if (!dataUrl) return;
// load data & set state
try {
const data = await fetch(dataUrl, {
signal: controller.signal,
});
setLoadedData(data);
} catch (e) {
console.error(`useData failed for url ${dataUrl}\n${e}.`);
}
}
getData(dataUrl);
// clean up the last request before running
// useEffect for on the next url
return () => {
controller.abort();
};
}, [dataUrl]);
// return data in the hook's state, set by useEffect
return loadedData;
};