Created
June 19, 2020 16:57
-
-
Save GenesisSam/5238e8e38899e2ca71ba2557f2dbb41e to your computer and use it in GitHub Desktop.
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
import * as React from "react"; | |
import axios, { CancelTokenSource } from "axios"; | |
export default function useCancelToken( | |
identity?: any, | |
): { | |
current: CancelTokenSource; | |
cancelAndRenewal(): void; | |
} { | |
const cancelTokenSource: React.MutableRefObject< | |
CancelTokenSource | undefined | |
> = React.useRef(undefined); | |
const cancelAndRenewal = React.useCallback(() => { | |
if (cancelTokenSource.current) { | |
cancelTokenSource.current.cancel(); | |
cancelTokenSource.current = axios.CancelToken.source(); | |
} | |
// eslint-disable-next-line react-hooks/exhaustive-deps | |
}, [cancelTokenSource.current]); | |
if (!cancelTokenSource.current) { | |
cancelTokenSource.current = axios.CancelToken.source(); | |
} | |
React.useEffect( | |
() => () => { | |
if (cancelTokenSource.current) { | |
// cancelTokenSource.current.cancel(); | |
cancelTokenSource.current = axios.CancelToken.source(); | |
} | |
}, | |
[identity], | |
); | |
return { | |
current: cancelTokenSource.current, | |
cancelAndRenewal, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment