-
-
Save thinkawitch/25f622448c899f2908e4735638b7dfcf to your computer and use it in GitHub Desktop.
React hook for AbortController with reset
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
function useAbortController(runEffect=false, runLayoutEffect=false) { | |
const acRef = useRef() | |
const getAbortController = useCallback(() => { | |
if (!acRef.current) { | |
acRef.current = new AbortController() | |
} | |
return acRef.current | |
}, []); | |
if (runEffect) { | |
useEffect(() => { | |
return () => { | |
acRef.current && acRef.current.abort() | |
} | |
}, []) | |
} | |
if (runLayoutEffect) { | |
useLayoutEffect(() => { | |
return () => { | |
acRef.current && acRef.current.abort() | |
} | |
}, []) | |
} | |
const resetAbortController = useCallback(() => { | |
acRef.current = new AbortController() | |
}, []) | |
return [getAbortController, resetAbortController] | |
} |
Why wrap hooks in a condition?
Depends on your higher components logic, you may remove the conditions, leave "useEffect" and remove "useLayoutEffect".
@sagarpanchal You are right. My gist is a simple example with not changeable params of useAbortController.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example: onCancel aborts the submit process and creates new controller for one more submit.