0

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

enter image description here

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.

2
  • That's because the state is updated asynchronously and fetch is also async. Commented Dec 19, 2020 at 19:11
  • yeah now I get it. Commented Dec 19, 2020 at 19:25

3 Answers 3

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

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

  useEffect(()=>{
    const fetchData = async()=>{
      const res = await fetch('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 ? <Map eventData={eventData}/> : <Loader/>}
    </div>
  );
}
  
export default App;
Sign up to request clarification or add additional context in comments.

1 Comment

Now I understand it. And thanks for the tip. cheers!!!
1

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

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) //Here

return (
    <div> 
      {{!loading ? <Map eventData={eventData}/> : <Loader/>}}
    </div>
  );
}
  
export default App;

1 Comment

Yeah I think that is because setState() is asynchronous. Thanks!
0

`


function RecipesList() {

  

  //use effect to

  useEffect(() => {

    const getRecipesList = async () => {

      const response = await fetch("http://localhost:4000/recipe/allrecipes", {

        method: "GET",

      });

      const json = await response.json();

      if (response.ok) {

        setData(json);

        const allCategories = [

          "all",

          ...new Set(data.map((item) => item.category)),

        ];

        setCategories(allCategories);

      }

      

    };

    getRecipesList();

    //get all categories from data

  }, []);

  };

 

}

Want to populate categories array base on data array

Data array is populated from databse



`

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.