Skip to content Skip to sidebar Skip to footer

No Response From Fetch Api In React Useeffect Hook

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.

Solution 1:

setState is asynchronous so you can't see the updated value in the function where you set a new value, where you console.log(eventData), you need to do console.log(events) to see what you get from the response

And, by the way, I recommend you to set loading at true by default because you do your request when the component mounts const [loading,setLoading] = useState(true);, then you can remove the setLoading(true); in the function

functionApp() {
  const [eventData,setEventData] = useState([]);
  const [loading,setLoading] = useState(true);

  useEffect(()=>{
    const fetchData = async()=>{
      const res = awaitfetch('https://eonet.sci.gsfc.nasa.gov/api/v2.1/events');
      const {events} = await res.json();
    console.log(events)
      setEventData(events);
      setLoading(false);
    }

    fetchData();
  },[])
return (
    <div> 
      {!loading ? <MapeventData={eventData}/> : <Loader/>}
    </div>
  );
}
  
exportdefaultApp;

Solution 2:

The problem is that you're trying to get the value of eventData before the state is updated move console.log(eventData) outside useEffect like so

functionApp() {
  const [eventData,setEventData] = useState([]);
  const [loading,setLoading] = useState(false);

  useEffect(()=>{
    const fetchData = async()=>{
      setLoading(true);
      const res = awaitfetch('https://eonet.sci.gsfc.nasa.gov/api/v2.1/events');
      const {events} = await res.json();
      setEventData(events);
      setLoading(false);
    }

    fetchData();
  
  },[])

  console.log(eventData) //Herereturn (
    <div> 
      {{!loading ? <MapeventData={eventData}/> : <Loader/>}}
    </div>
  );
}
  
exportdefaultApp;

Post a Comment for "No Response From Fetch Api In React Useeffect Hook"