2021-09-24 13:56:42 +02:00
|
|
|
import { useRef, useEffect, useCallback } from 'react'
|
|
|
|
import axios, { CancelToken } from 'axios'
|
2022-11-08 18:17:22 +01:00
|
|
|
|
2021-09-24 13:56:42 +02:00
|
|
|
export const useCancelToken = (): (() => CancelToken) => {
|
|
|
|
const axiosSource = useRef(null)
|
2022-11-08 18:17:22 +01:00
|
|
|
|
2021-09-24 13:56:42 +02:00
|
|
|
const newCancelToken = useCallback(() => {
|
|
|
|
axiosSource.current = axios.CancelToken.source()
|
2022-11-08 18:17:22 +01:00
|
|
|
return axiosSource?.current?.token
|
2021-09-24 13:56:42 +02:00
|
|
|
}, [])
|
|
|
|
|
|
|
|
useEffect(
|
|
|
|
() => () => {
|
|
|
|
if (axiosSource.current) axiosSource.current.cancel()
|
|
|
|
},
|
|
|
|
[]
|
|
|
|
)
|
|
|
|
|
|
|
|
return newCancelToken
|
|
|
|
}
|