Created
November 29, 2022 22:16
-
-
Save jinsley8/15796e574ff0783a41019a7997bddda8 to your computer and use it in GitHub Desktop.
A hook that uses axios to fetch data
This file contains hidden or 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
import axios, { AxiosRequestConfig } from 'axios'; | |
import { useEffect, useState } from 'react'; | |
axios.defaults.baseURL = `${process.env.NEXT_PUBLIC_SITE_URL}/api/${process.env.NEXT_PUBLIC_API_VERSION}`; | |
export const useAxiosFetch = (params: AxiosRequestConfig<any>) => { | |
const [data, setData] = useState<any>(null); | |
const [error, setError] = useState<any>(null); | |
const [loading, setLoading] = useState<boolean>(true); | |
const fetchData = async (): Promise<void> => { | |
try { | |
const response = await axios.request(params); | |
setData(response.data); | |
} catch (error) { | |
if (axios.isAxiosError(error)) { | |
setError('Axios Error with Message: ' + error.message); | |
} else { | |
setError(error); | |
} | |
setLoading(false); | |
} finally { | |
setLoading(false); | |
} | |
}; | |
useEffect(() => { | |
fetchData(); | |
// eslint-disable-next-line react-hooks/exhaustive-deps | |
}, []); | |
return [data, error, loading, fetchData] as const; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment