AbortController is a web standard for aborting requests via a signal
.
This is quite important in React 18 due to the double firing of useEffects in dev mode. We probably want to cancel redundant request when components mount and re-mount.
useEffect(() => {
// Setup our abortController
const abortController = new AbortController();
const getAsyncData = async () => {
try {
const res = await fetch(`/api/some-data?query=${queryParam}`, {
method: 'POST',
signal: abortController.signal,
});
const json = await res.json();
const clientSecret = json.clientSecret;
setStripeState({ state: 'success', clientSecret });
} catch (e) {
if (!abortController.signal.aborted) {
setStripeState({
state: 'error',
message: 'Unknown error',
});
}
}
};
// if the component unmounts or he queryParam changes we can cancel the fetch request like this:
return () => {
abortController.abort();
};
}, [queryParam]);