Created
August 14, 2019 10:13
-
-
Save SevenOutman/d2efe04ac6a47dbeff1987208b45f8b3 to your computer and use it in GitHub Desktop.
React hook for async callback that automatically aborts on component unmount.
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
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Interesting use of an abort that doesn't rely on abort controller, thanks for sharing