0
votes

Trying to figure out why the state is not being set after I fetch the data. Here is the code I am using...

const [data, setData]: any = useState({ items: [] });

useEffect(() => {
    async function fetchData() {
        const repsonse: any = await fetch('https://hn.algolia.com/api/v1/search?query=react');
        const result: any = await repsonse.json();
        //console.log(result);
        setData(result.hits);
    }
    fetchData();
}, []);

console.log(data);

In the example above I am using hooks for useState(). Then I use a useEffect to do a fetch request. I use the setData function to set the state that I got from the request.

But when I console.log the data I get an empty array. Anyone know why this is happening? Might be something simple that I am missing.

1
Remove await from await repsonse.json(); - ravibagul91
Your code is asynchronous so data is empty at the time of the logging. Put the console.log right after setData. - Gaƫl S
The code looks correct! - wiesson
@ravibagul91 await should be there, as response.json() is indeed a promise as well. What does the result say? Any errors in your console? Add a try/catch. - Goodbye StackExchange

1 Answers

0
votes

useEffect is run after the render happens and since you initially your state is empty the console.log outside of useEffect will show you the empty data itself. However, once the data is fetched you will see the updated data in the second render. Also, you need to setState to items instead of directly passing the obtained list

const { useState, useEffect } = React;
const App = () => {
  const [data, setData] = useState({ items: [] });

  useEffect(() => {
      async function fetchData() {
          const repsonse= await fetch('https://hn.algolia.com/api/v1/search?query=react');
          const result = await repsonse.json();
          //console.log(result);
          setData({items: result.hits});
      }
      fetchData();
  }, []);

  console.log(data);
     return <pre>{JSON.stringify(data.items null, 4)}</pre>

}

Working demo