Created
June 2, 2021 18:28
-
-
Save harshaktg/37f25f5142e85c71bc3aee46027a5a99 to your computer and use it in GitHub Desktop.
useAxios - Step 3 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 = () => { | |
const [response, setResponse] = useState(null); | |
const [error, setError] = useState(null); | |
const [loading, setLoading] = useState(false); | |
const fetchData = async () => { | |
setLoading(true); | |
try { | |
const res = await axios.get('/posts'); | |
setResponse(res.data); | |
setError(null); | |
} catch (err) { | |
setError(err); | |
} finally { | |
setLoading(false); | |
} | |
}; | |
useEffect(() => { | |
fetchData(); | |
}, []); | |
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