Skip to content

Instantly share code, notes, and snippets.

@lawrence79
Created June 9, 2021 15:42
Show Gist options
  • Save lawrence79/fc075774d9408ed71153401411ec1fd4 to your computer and use it in GitHub Desktop.
Save lawrence79/fc075774d9408ed71153401411ec1fd4 to your computer and use it in GitHub Desktop.
axios hook
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