Created
August 1, 2020 09:30
-
-
Save ravuthz/6d095c4cfe79a12151b0a3f51545a1df to your computer and use it in GitHub Desktop.
[react-ts-hooks] React Ts Hook #react-ts #hook
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 axios, { AxiosResponse } from 'axios'; | |
import { useEffect, useState } from 'react'; | |
const useAxiosFetch: any = ( | |
url: string, | |
params: any, | |
headers: any, | |
timeout?: number | |
) => { | |
const [data, setData] = useState<AxiosResponse | null>(null); | |
const [error, setError] = useState(null); | |
const [loading, setLoading] = useState(true); | |
useEffect(() => { | |
let mouted: boolean = true; | |
const source: any = axios.CancelToken.source(); | |
axios | |
.get(url, { | |
params, | |
headers, | |
timeout, | |
cancelToken: source.token, | |
}) | |
.then((a) => { | |
if (mouted) { | |
setData(a.data); | |
setError(null); | |
setLoading(false); | |
} | |
}) | |
.catch((e: any) => { | |
if (mouted) { | |
setData(null); | |
setError(e); | |
setLoading(false); | |
if (axios.isCancel(e)) { | |
console.log(`request cancelled: ${e.message}`); | |
} else { | |
console.log(`another error happened: ${e.message}`); | |
} | |
} | |
}); | |
return () => { | |
mouted = false; | |
source.cancel('Cancelling in cleanup'); | |
}; | |
}, [url, params, headers, timeout]); | |
return { | |
data, | |
error, | |
loading, | |
}; | |
}; | |
export default useAxiosFetch; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment