Skip to content

Instantly share code, notes, and snippets.

@SevenOutman
Created August 14, 2019 10:13
Show Gist options
  • Save SevenOutman/d2efe04ac6a47dbeff1987208b45f8b3 to your computer and use it in GitHub Desktop.
Save SevenOutman/d2efe04ac6a47dbeff1987208b45f8b3 to your computer and use it in GitHub Desktop.
React hook for async callback that automatically aborts on component unmount.
export default function useAbortableAsyncCallback(callback, inputs) {
const abortHandleRef = useRef();
const runAbortHandle = useCallback(() => {
if (abortHandleRef.current) {
abortHandleRef.current();
}
}, []);
const asyncCallback = useCallback(callback, inputs);
const abortableAsyncCallback = useCallback((...args) => {
runAbortHandle();
const abortPromise = new Promise((resolve) => {
abortHandleRef.current = resolve;
});
const promise = asyncCallback(...args);
Promise.race([promise, abortPromise]);
return promise;
}, [asyncCallback]);
useEffect(() => {
return () => {
runAbortHandle();
}
}, []);
return abortableAsyncCallback;
}
@cmdcolin
Copy link

Interesting use of an abort that doesn't rely on abort controller, thanks for sharing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment