Listing 16-2: Loading initial data in a class component
import {Component} from 'react';
class NewsFeed extends Component {
constructor(props){
super(props);
this.state={
news:[]
}
}
componentDidMount(){
fetch('https://newsapi.org/v2/top-headlines?country=us&apiKey=[YOUR KEY]')
.then(response => response.json())
.then(data => {
this.setState({news:data.articles})})
.catch(error => console.error(error))
}
render(){
const todaysNews = this.state.news.map((article)=>{
return (<p>{article.title}</p>);
})
return(
<h1>Today's News</h1>
{todaysNews}
)
}
}
export default NewsFeed;
Download the examples, report issues, and ask/answer questions in the discussion area by visiting the book's github page. All of the code for the book is also available on codesandbox.io for you to play around with.
ReactJS Foundations is published by John Wiley and Sons, Inc and is available in paperback and eBook.