I have a problem when I close a tab and then I undo that action. It basically executes all the cleanup functions in the component, aborting the new fetches that are needed to load the component (old cleanup functions are aborting new fetches). For Chrome and Firefox, it works fine. For what I have tested, it happens only on Safari.
React.useEffect(() => {
const abortController = new AbortController();
fetch(`${URL}${API.mediaDetails}`
+ `?id=${encodeURIComponent(props.match.params.id)}`
+ `&type=${encodeURIComponent(props.match.params.type)}`
+ `&lang=${encodeURIComponent(props.match.params.locale?.slice(0, 2))}`, {
signal: abortController.signal,
timeout: DOWNLOAD_HUB_REQ_TIMEOUT
}).then((res) => res.json()).then((res) => {
res.type = props.match.params.type;
return setDetails(res);
}).catch((err) => {
setDetails(null);
setError(err);
});
return () => abortController.abort();
}, [props.match.params]);
The cleanup function (to abort the request) will be run whenever the component is removed from the DOM. When you close the tab, that component (and in fact, all of the components on the page) will be removed, which means all their cleanup functions will be run.
This is normally what you want. If you go to /foo/1
, and you start fetching data for foo #1 ... but then you change pages to /foo/2
... you want to abort the fetch for foo #1! You don't need it anymore, so why have it slow down the request for foo #2?
However, if you for some reason don't want this behavior, you could always set some sort of flag (eg. dontCleanup
) before the user leaves, and then check for that flag in your cleanup function.
NOTE: Individual browsers (eg. Safari) may have bugs that violate this behavior. Upgrading to the latest browser version should resolve it.