Created
August 16, 2021 13:12
-
-
Save popescuaaa/6dbc332f5e7526b6982dbb053bed9ee7 to your computer and use it in GitHub Desktop.
react typescript axios 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
/* 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