Skip to content

Instantly share code, notes, and snippets.

@joeypy
Last active December 19, 2022 23:24
Show Gist options
  • Save joeypy/b16e5292c7fc447804103d5dc276aafc to your computer and use it in GitHub Desktop.
Save joeypy/b16e5292c7fc447804103d5dc276aafc to your computer and use it in GitHub Desktop.
Custom hook for request Axios
import axios from 'axios';
import { useEffect, useState, useRef } from 'react';
interface ResponseApi {
data: any;
isLoading: boolean;
isError: Error | null;
errorMessage: any;
refetch: (params?: any) => void;
}
interface Props {
url: string;
initialParams?: any;
initialFetch?: boolean;
}
export const useAxios = ({
url,
initialParams,
initialFetch = true,
}: Props): ResponseApi => {
// Return
const [data, setData] = useState();
const [isLoading, setIsLoading] = useState(false);
const [isError, setIsError] = useState(null);
const [errorMessage, setErrorMessage] = useState(null);
// Refetching
const [isRefetching, setIsRefetching] = useState(false);
const [params, setParams] = useState<any>(initialParams);
const initialCall = useRef(initialFetch);
const refetch = (paramsProps: any) => {
if (paramsProps) {
setParams(paramsProps);
}
setIsRefetching(!isRefetching);
};
useEffect(() => {
if (!initialCall.current) {
initialCall.current = true;
return;
}
let unmounted = false;
let source = axios.CancelToken.source();
(async () => {
setIsError(null);
setIsLoading(true);
await axios.get(url, {
params,
cancelToken: source.token,
})
.then((res) => {
if (!unmounted) {
setData(res.data);
}
})
.catch((error: any) => {
if (!unmounted) {
setIsError(error);
setErrorMessage(error.message);
if (axios.isCancel(error)) {
console.log(`request cancelled:${error.message}`);
} else {
console.log('Error ocurred: ' + Error(error));
}
}
})
.finally(() => setIsLoading(false));
})();
return () => {
unmounted = true;
source.cancel('Cancelling in cleanup');
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [url, isRefetching]);
return { data, isLoading, isError, errorMessage, refetch };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment