Skip to content

Instantly share code, notes, and snippets.

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