Created
March 4, 2020 11:11
-
-
Save MRezaSafari/d77060ad36a8d9e2045e9752896b4675 to your computer and use it in GitHub Desktop.
useApi
This file contains 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 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