I am trying to use the fetch API in React useEffect hook to make a get request but I am not able to Print my response as expected. I am only getting an empty array as the response.
This is my code.
function App() {
const [eventData,setEventData] = useState([]);
const [loading,setLoading] = useState(false);
useEffect(()=>{
const fetchData = async()=>{
setLoading(true);
const res = await fetch('https://eonet.sci.gsfc.nasa.gov/api/v2.1/events');
const {events} = await res.json();
setEventData(events);
setLoading(false);
}
fetchData();
console.log(eventData)
},[])
return (
<div>
{{!loading ? <Map eventData={eventData}/> : <Loader/>}}
</div>
);
}
export default App;
this is my output
But if write the console.log statement after the useEffect hook I am getting the expected output. I don't understand why it's behaving in this way. It would be much appreciated if someone can explain the reason for this. Thanks in Advance.
