Skip to content

Instantly share code, notes, and snippets.

@ravuthz
Created August 1, 2020 09:30
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 ravuthz/6d095c4cfe79a12151b0a3f51545a1df to your computer and use it in GitHub Desktop.
Save ravuthz/6d095c4cfe79a12151b0a3f51545a1df to your computer and use it in GitHub Desktop.
[react-ts-hooks] React Ts Hook #react-ts #hook
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