I was trying to fetch API with react.js but on first render its gives nothing and the second render its gives data. This makes it so when I try to access the data later for an image I get an error:
TypeError: Cannot read property 'news.article' of undefined, because it is initially empty.
How can I solve this?
Here is my code ..
import React, { useEffect, useState } from 'react';
const HomeContent = () => {
const [news, updateNews] = useState([]);
console.log(news);
useEffect(() => {
const api = 'http://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=940c56bd75da495592edd812cce82149'
fetch(api)
.then(response => response.json())
.then(data => updateNews(data))
.catch((error) => console.log(error))
}, [])
return (
<>
</>
);
};
export default HomeContent;

news(let alonenews.articlesso that code can't produce that error. (And ifnewsis going to get a property calledarticlesthen it doesn't make sense to initialize it to an empty array).loadingstate, that you set tofalsewhen the request finished. You can then render some kind of loading indicator, whileloadingis stilltrue. For a more sophisticated app you will also need some state to handle errors while fetching the data.