Created
June 9, 2021 15:42
-
-
Save lawrence79/fc075774d9408ed71153401411ec1fd4 to your computer and use it in GitHub Desktop.
axios hook
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 { useState, useEffect } from 'react'; | |
import axios from 'axios'; | |
axios.defaults.baseURL = process.env.API_URL; | |
const useAxios = ({ url, method, body = null, headers = null }) => { | |
const [response, setResponse] = useState(null); | |
const [error, setError] = useState(''); | |
const [loading, setloading] = useState(true); | |
const fetchData = () => { | |
axios[method](url, JSON.parse(headers), JSON.parse(body)) | |
.then(res => { | |
setResponse(res.data); | |
}) | |
.catch(err => { | |
setError(err); | |
}) | |
.finally(() => { | |
setloading(false); | |
}); | |
}; | |
useEffect(() => { | |
fetchData(); | |
}, [method, url, body, headers]); | |
return { response, error, loading }; | |
}; | |
export default useAxios; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment