I'm currently working on creating a news app that showcases the top 20 articles from each country. However, I encountered an issue when trying to set my state inside a loop - all entries were being overwritten and only the last one would display. Any suggestions on how I can avoid this problem and show multiple entries without overriding the previous ones? Thank you for your help!
//the code snippet below is located within my App.js file under the App component
getNews = async (e) => {
e.preventDefault();
const country = e.target.elements.country.value;
const api_call = await fetch(this.buildURL(country));
const data = await api_call.json();
if (country) {
console.log(data);
//I modified this section to display the first article out of 20
this.setState({
title: data.articles[0].title,
image: data.articles[0].urlToImage,
description: data.articles[0].description,
author: data.articles[0].author,
link: data.articles[0].url,
err: ""
});
}
else {
this.setState({
title: undefined,
image: undefined,
description: undefined,
author: undefined,
link: undefined,
err: "Please enter a valid country"
});
}
}
render() {
return(
<div>
<Titles />
<Form getNews={this.getNews}/>
<News title={this.state.title}
image={this.state.image}
description={this.state.description}
author={this.state.author}
link={this.state.link}
err={this.state.err}
/>
</div>
);
}
This is a project aimed at beginners so please consider that in your responses haha.