I'm trying to render data from my server to my React front end. The axios calls work and return test data that is in my database, but I can't seem to set the state with this data and then render it onto the page. I've spent hours implementing different approaches and reading every related problem, but nothing seems to work. What am I missing? The only thing that will render is the "no results to display" and console.logging articles yield an empty array (after setting its state).
I've tried setArticles({articles: data}), setArticles(data)...nothing works.
The console.log(data) returns 0: {_id: "5de17f5639103b3f430571c4", title: "testing", link: "www.test.com", headline: "test headline", summary: "test summary"} length: 1 proto: Array(0)
function Home(){
const [articles, setArticles] = useState([]);
useEffect(() => {
let initialArticles = [];
axios.get("/api/articles")
.then(response => {
let data = response.data;
initialArticles = data.map(article => {
return article
});
return initialArticles
}).then(data => {
console.log(data)
setArticles({
headline: data.headline, URL: data.URL, summary: data.summary, comment: data.comment
})
console.log(articles)
})
}, [])
return (
<div id="homeBackground">
<Container id="homeContainer">
<h1>News Scraper</h1>
<h4>Automatically grab the latest headlines.</h4>
{articles.length ? (
<ul>
{articles.map(el => (
<li key={el._id}>
<a href={el.URL}>
<strong>
{el.headline}
</strong>
</a>
</li>
))}
</ul>
) : (
<h3>No Results to Display</h3>
)}
</Container>
</div>
)
};
export default Home;
setArticles(data)instead