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.
The initial value of state.articles
is this.articles
which is undefined
.
At some point in the future, you'll assign a useful value to that property, but until then you can't treat it like the array it will be in the future but isn't yet.
Test the value and do something different.
eg
(!this.state.articles && <Loading />}
{this.state.articles && this.state.articles.map(element=> console.log(element))}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.