Skip to content

Instantly share code, notes, and snippets.

@MattBevis
Created June 13, 2022 14:37
Show Gist options
  • Save MattBevis/ac52e74f84ca5688b3c8e5a45f91f8f2 to your computer and use it in GitHub Desktop.
Save MattBevis/ac52e74f84ca5688b3c8e5a45f91f8f2 to your computer and use it in GitHub Desktop.
useAxios.js
/**
* This is the highest level hook for making HTTP requests. It's just a wrapper for basic HTTP requests.
*/
function useAxios() {
const [isLoading, setIsLoading] = React.useState(false);
const { getAccessTokenSilently } = useAuth0();
axios.defaults.baseURL = process.env.REACT_APP_BASE_URL;
const getRequest = async (url) => {
setIsLoading(true);
const token = await getAccessTokenSilently();
return axios
.get(url, { headers: { Authorization: `Bearer ${token}` } })
.then((res) => res.data)
.finally(() => setIsLoading(false));
};
const postRequest = async (url, data) => {
setIsLoading(true);
const token = await getAccessTokenSilently();
return axios
.post(url, data, { headers: { Authorization: `Bearer ${token}` } })
.then((res) => res.data)
.finally(() => setIsLoading(false));
};
const putRequest = async (url, data) => {
setIsLoading(true);
const token = await getAccessTokenSilently();
return axios
.put(url, data, { headers: { Authorization: `Bearer ${token}` } })
.then((res) => res.data)
.finally(() => setIsLoading(false));
};
const patchRequest = async (url, data) => {
setIsLoading(true);
const token = await getAccessTokenSilently();
return axios
.patch(url, data, { headers: { Authorization: `Bearer ${token}` } })
.then((res) => res.data)
.finally(() => setIsLoading(false));
};
const deleteRequest = async (url, data) => {
setIsLoading(true);
const token = await getAccessTokenSilently();
return axios
.delete(url, { data, headers: { Authorization: `Bearer ${token}` } })
.then((res) => res.data)
.finally(() => setIsLoading(false));
};
const getFileRequest = async (url) => {
setIsLoading(true);
const token = await getAccessTokenSilently();
return axios
.get(url, { headers: { Authorization: `Bearer ${token}` }, responseType: 'arraybuffer' })
.then((res) => res.data)
.finally(() => setIsLoading(false));
};
const postFileRequest = async (url, data) => {
setIsLoading(true);
const token = await getAccessTokenSilently();
return axios
.post(url, data, { headers: { Authorization: `Bearer ${token}` }, responseType: 'arraybuffer' })
.then((res) => res.data)
.finally(() => setIsLoading(false));
};
return {
isLoading,
getRequest,
postRequest,
putRequest,
patchRequest,
deleteRequest,
getFileRequest,
postFileRequest
};
}
export default useAxios;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment