// use-fetch-data.js
import { useEffect, useState} from 'react';
import axios from 'axios';
const useFetchData = () => {
const [data, setData] = useState({});
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchData = async () => {
try {
const { data: response } = await axios.get('/stuff/to/fetch');
setData(response);
} catch (error) {
console.error(error)
}
setLoading(false);
};
fetchData();
}, []);
return {
data,
loading,
};
};
export default useFetchData;
//mycomponent.js
import React from 'react';
import useFetchData from './hooks/use-fetch-data.js'
const MyComponent = () => {
const {
data,
loading,
} = useFetchData();
return (
<div>
{loading && <div>Loading</div>}
{!loading && (
<div>
<h2>Doing stuff with data</h2>
{data.map(item => (<span>{item.name}</span>))}
</div>
)}
</div>
)
}
export default MyComponent;