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?
useEffectis 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 ifcoronaData["Global"]is defined before accessing any property on it. Using optional chaining, you can do:coronaData?.["Global"]?.["TotalConfirmed"]