Skip to content

Instantly share code, notes, and snippets.

@andrIvash
Created February 19, 2021 14:08
Show Gist options
  • Save andrIvash/4c9ea1456b1067fb30d58684eb7901cd to your computer and use it in GitHub Desktop.
Save andrIvash/4c9ea1456b1067fb30d58684eb7901cd to your computer and use it in GitHub Desktop.
creating a cancelable promises
/**
* creating a cancelable promises allows you to ensure that callbacks will only be executed
* if the context is still appropriate for it.
* https://medium.com/trabe/avoid-updates-on-unmounted-react-components-2fbadab17ad2
*
* useEffect(() => {
* const api = useCancellablePromises();
* const fetchDataCancellablePromise = fetchData();
* api.appendPendingPromise(fetchDataCancellablePromise);
*
* fetchDataCancellablePromise.promise
* .then(() => {});
*
* return () => {
* api.removePendingPromise(fetchDataCancellablePromise);
* }
* }
*/
const useCancellablePromises = () => {
const pendingPromises = useRef([]);
const appendPendingPromise = (promise: Promise<any>) =>
pendingPromises.current = [...pendingPromises.current, promise];
const removePendingPromise = (promise: Promise<any>) =>
pendingPromises.current = pendingPromises.current.filter(p => p !== promise);
const clearPendingPromises = () => pendingPromises.current.map(p => p.cancel());
const api = {
appendPendingPromise,
removePendingPromise,
clearPendingPromises,
};
return api;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment