Listing 16-3: Loading initial data in a function component
import {useState,useEffect} from 'react';
const NewsFeedFunction = () => {
const [news,setNews] = useState([]);
useEffect(()=> {
fetch('https://newsapi.org/v2/top-headlines?country=us&apiKey=[YOUR KEY]')
.then(response => response.json())
.then(data => {
setNews(data.articles)
})
.catch(error => console.error(error))
},[])
const todaysNews = news.map((article)=>{
return (<p>{article.title}</p>);
})
return(
<h1>Today's News</h1>
{todaysNews}
)
}
export default NewsFeedFunction;
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.