Skip to content

Instantly share code, notes, and snippets.

@harshaktg
Created June 2, 2021 18:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harshaktg/37f25f5142e85c71bc3aee46027a5a99 to your computer and use it in GitHub Desktop.
Save harshaktg/37f25f5142e85c71bc3aee46027a5a99 to your computer and use it in GitHub Desktop.
useAxios - Step 3 custom hook file
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