Skip to content

Instantly share code, notes, and snippets.

@MRezaSafari
Created March 4, 2020 11:11
Show Gist options
  • Save MRezaSafari/d77060ad36a8d9e2045e9752896b4675 to your computer and use it in GitHub Desktop.
Save MRezaSafari/d77060ad36a8d9e2045e9752896b4675 to your computer and use it in GitHub Desktop.
useApi
import axios from 'axios';
import {useCallback, useEffect, useState} from 'react';
const useApi = (url, method, data = {}, options = {}) => {
const [response, setResponse] = useState(null);
const [loading, setLoading] = useState(true);
const fetch = useCallback(async () => {
const req = await axios({url, method, data, ...options});
try {
if (req.status < 200 || req.status > 200) {
//Show some errors in someway
} else {
setResponse(req.data);
}
setLoading(false);
} catch (error) {
//Show some errors in someway
setLoading(false);
}
});
useEffect(() => {
fetch();
}, []);
return [response, loading];
};
export default useApi;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment