Created
June 23, 2022 03:08
-
-
Save code0monkey1/6a33b4247cd413528fb552c49132e4e8 to your computer and use it in GitHub Desktop.
A custom hook for getting data using axios from apis
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
| import { useEffect,useState } from 'react' | |
| import axios from 'axios' | |
| import logger from '../utils/logger' | |
| const useUrl = (description) => { | |
| const [data,setData] = useState(null) | |
| const [status,setStatus] = useState(null) | |
| const [url,setUrl] = useState(null) | |
| const [loading,setLoading] = useState(false) | |
| useEffect(() => { | |
| if(!url) return | |
| const source = axios.CancelToken.source() | |
| setLoading(true) | |
| axios.get(url,{ cancelToken: source.token }) | |
| .then(response => { | |
| setData(response.data) | |
| setStatus(response.status) | |
| logger.success( | |
| `${description.toUpperCase()} : | |
| Response status: ${response.status} | |
| Response data: ${JSON.stringify(response.data , null, 2)}` | |
| ) | |
| } | |
| ) | |
| .catch(error => { | |
| if(axios.isCancel(error)) { | |
| logger.warn('Axios request cancelled! ') | |
| return | |
| } | |
| logger.error('Axios request failed! ',error.response.data) | |
| setData(error) | |
| setStatus(error.response.status) | |
| } | |
| ) | |
| .finally(() => { | |
| setLoading(false) | |
| } | |
| ) | |
| return () => source.cancel() | |
| },[url]) | |
| const clearData=() => { | |
| setData(null) | |
| setStatus(null) | |
| setUrl(null) | |
| setLoading(false) | |
| } | |
| return ( | |
| { data,status,setUrl,clearData ,loading } | |
| ) | |
| } | |
| export default useUrl |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment