I am trying to fetching data from newsapi website. It gives me data as array like object format.
Now, my goal is to iterate this data and display my newsItem component. Here is my code below.
export class News extends Component {
constructor(){
super()
this.state = {
articles: this.articles
}
}
componentDidMount(){
fetch(`https://newsapi.org/v2/top-headlines?country=us&apiKey=d21fe13361b94006b816f98a7c005003`)
.then(res =>res.json())
.then(data => this.setState({articles:data.articles}))
}
render() {
return <div className='container my-3'>
<h1 className='my-3'>NewsDonkey - Top Headlines</h1>
<div className="row">
{this.state.articles.map(element=> console.log(element))}
<div className="col-md-4">
<NewsItem/>
</div>
</div>
</div>;
}
}
export default News;
but, browser shows can’t read properties of undefined. Here is the error image.
Now, you may say that data may be in object format that’s why map method is not working. I tried same coding in JS: articles.map(element=> console.log(element)) it extracted data perfectly. Please help me if you find any error in my coding.