Last active
June 2, 2021 18:40
-
-
Save harshaktg/de70c7030eb7b716643f6629411b559a to your computer and use it in GitHub Desktop.
useAxios - Step 4 custom hook file
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 { useState, useEffect } from 'react'; | |
import axios from 'axios'; | |
axios.defaults.baseURL = 'https://jsonplaceholder.typicode.com'; | |
const useAxios = (params) => { | |
const [response, setResponse] = useState(null); | |
const [error, setError] = useState(null); | |
const [loading, setLoading] = useState(false); | |
const fetchData = async (params) => { | |
setLoading(true); | |
try { | |
const res = await axios.request(params); | |
setResponse(res.data); | |
setError(null); | |
} catch (err) { | |
setError(err); | |
} finally { | |
setLoading(false); | |
} | |
}; | |
useEffect(() => { | |
fetchData(params); | |
}, []); | |
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