Created
February 19, 2021 14:08
-
-
Save andrIvash/4c9ea1456b1067fb30d58684eb7901cd to your computer and use it in GitHub Desktop.
creating a cancelable promises
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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