Last active
October 8, 2021 17:46
-
-
Save karpolan/c1885abda9f02de3d4ce47d1ac6cc457 to your computer and use it in GitHub Desktop.
useAxios() hook with separate (url, method, body, headers) params
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
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