2

I am learning react and making a project that has a component that needs to display async information:

function ShortStatistic() {

    const [coronaData, setCoronaData] = useState([]);
    
    useEffect(() => {
        (async () => {
            const fetchedPosts = await getCoronaData();
            setCoronaData(fetchedPosts);
        })();
        console.log("UseEffectCall");
    }, []);

    async function getCoronaData() {
        const URL = "https://api.covid19api.com/summary";
        const requestOptions = {
            method: 'GET',
            redirect: 'follow'
        };
      
        const response = await fetch(URL, requestOptions);
        const data = await response.json();
        return data;
    }


    return (
        <div className="stat">
             <div className="stat_infected">
                  Infected:
                    <span className="infected_numbers">
                         {(coronaData["Global"]["TotalConfirmed"])}
                    </span>
              </div>
        </div>
    )
}

But I am getting an error: "TypeError: Cannot read property 'TotalConfirmed' of undefined", what means setCoronaData() didn't work. Also, there is no message output from the useEffect hook (console.log("UseEffectCall");) in the console. What is the problem?

2
  • useEffect is called after the initial render, so during the initial render, coronaData["Global"] is undefined. As a result, coronaData["Global"]["TotalConfirmed"] causes an error because its like doing: undefined["TotalConfirmed"]. You need to check if coronaData["Global"] is defined before accessing any property on it. Using optional chaining, you can do: coronaData?.["Global"]?.["TotalConfirmed"] Commented Jul 3, 2021 at 11:46
  • @Yousaf Thanks for the help! Then I'll probably do an initial verification of coronaData or write an initial state-template for it. Commented Jul 3, 2021 at 12:29

1 Answer 1

2

for first render your coronaData variable is an empty array [] and when you call

coronaData["Global"]["TotalConfirmed"] 

it means undefined

You can use

coronaData?.["Global"]?.["TotalConfirmed"]
Sign up to request clarification or add additional context in comments.

Comments

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.