0

I'm calling an API inside the useEffect hook and trying to update my state covidData but my array remains empty even after calling the setData function:

const [covidData, setData] = useState([]);

useEffect(() => {
        async function getGlobalData() {

            let response = await fetch('https://api.covid19api.com/summary');
            let jsonResponse = await response.json();
            const globalData = jsonResponse.Global;

            //setting covidData
            setData([...covidData, {recovered: globalData.TotalRecovered}])
            console.log(covidData); //covidData is empty
        }

        getGlobalData()
    }, [])

what am I doing wrong?

Huma Ali
  • 1,759
  • 7
  • 40
  • 66
  • 1
    do console outside of the useEffect and see if it's working. Currently, your console inside of useEffect is empty because setStates run asynchonously meaning your console log is giving you old result not the updated one. – rakesh shrestha Feb 28 '21 at 15:15
  • @ReyYoung Yes its showing up outside the useEffect block – Huma Ali Feb 28 '21 at 15:21
  • try so see in `Network` tab how response looks like – StepUp Feb 28 '21 at 15:23

2 Answers2

0

Your code is correct, the state is updated asynchronously, it's normal your console.log will not display your state after your setState.

Soufiane Boutahlil
  • 2,554
  • 1
  • 7
  • 13
  • 1
    covidData is an array, you need to iterate between items of covidData like this: covidData.map(covidDataItem =>
    {covidDataItem.recovered}
    )
    – Soufiane Boutahlil Feb 28 '21 at 15:19
0

It is how react works, when you change state of something, react creates new instance of virtual dom.

So when you change state of covidData the value you set will be in new instance and the console.log is still in that old instance so it logs old value which is empty as you set when using useState.

Try logging with button onClick event and you will see your data or you can check with React Dev Tools

Also you can refactor your code as

useEffect(async () => {

        let response = await fetch('https://api.covid19api.com/summary');
        let jsonResponse = await response.json();
        const globalData = jsonResponse.Global;

            //setting covidData
            setData([...covidData, {recovered: globalData.TotalRecovered}])
           
    }, [])

More on virtual dom

  1. React Docs

  2. What is virtual DOM

timbersaw
  • 620
  • 5
  • 9