Skip to content

Instantly share code, notes, and snippets.

@popescuaaa
Created August 16, 2021 13:12
Show Gist options
  • Save popescuaaa/6dbc332f5e7526b6982dbb053bed9ee7 to your computer and use it in GitHub Desktop.
Save popescuaaa/6dbc332f5e7526b6982dbb053bed9ee7 to your computer and use it in GitHub Desktop.
react typescript axios hook
/* eslint-disable react-hooks/exhaustive-deps */
import { useEffect, useState } from "react";
import axios, { Method } from "axios";
/**
* https://github.com/ali-master/react-typescript-hooks-sample
*/
const useFetch = (
url: string,
method: Method,
body: any
): [boolean, string | null, any] => {
const [loading, setLoading] = useState<boolean>(false);
const [data, setData] = useState<any>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
setLoading(true);
const fetchData = async () => {
try {
const response = await axios({
url: url,
method: method,
data: body,
});
const data = response?.data;
setData(data);
} catch (error: any) {
setError(error);
} finally {
setLoading(false);
}
};
fetchData().then((r) => r);
}, [url]);
return [loading, error, data];
};
export { useFetch };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment