Created
January 4, 2021 05:59
-
-
Save jwchang0206/93a15ee1ea562beb5571a9fd1d75b1f9 to your computer and use it in GitHub Desktop.
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
import { useCallback, useEffect, useRef } from 'react'; | |
import axios, { Canceler } from 'axios'; | |
export const useCancelTokens = () => { | |
const cancelTokens = useRef<Canceler[]>([]); | |
// Add a cancel token in this hooks and return a generated token | |
const addCancelToken = useCallback(() => { | |
const { cancel, token } = axios.CancelToken.source(); | |
cancelTokens.current.push(cancel); | |
return token; | |
}, []); | |
// Cancel all requests | |
const cancelAll = useCallback(() => { | |
cancelTokens.current.forEach((canceler) => canceler()); | |
}); | |
useEffect(() => { | |
// Cancel all requests on unmount cycle | |
return () => { | |
cancelAll(); | |
}; | |
}, []); | |
return { | |
cancelTokens, | |
addCancelToken, | |
cancelAll, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment