-
-
Save thinkawitch/25f622448c899f2908e4735638b7dfcf to your computer and use it in GitHub Desktop.
React hook for AbortController with reset
This file contains 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] | |
} |
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.