Skip to content

Instantly share code, notes, and snippets.

@thinkawitch
Forked from kentcdodds/abort-controller.js
Last active July 6, 2022 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thinkawitch/25f622448c899f2908e4735638b7dfcf to your computer and use it in GitHub Desktop.
Save thinkawitch/25f622448c899f2908e4735638b7dfcf to your computer and use it in GitHub Desktop.
React hook for AbortController with reset
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]
}
@thinkawitch
Copy link
Author

Example: onCancel aborts the submit process and creates new controller for one more submit.

const [ getAC, resetAC ] = useAbortController(true);

const onSubmit = useCallback(data => {
    dispatch(textRoomCreate({ data, signal: getAC().signal }))
}, []);

const onCancel = useCallback(() => {
    getAC().abort();
    resetAC();
}, []);

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