I am trying to make a mock news react app and I am using newsapi's node package. This returns a response that has an array of objects inside one object. I set the state to the response of the newsapi function and when I log it to the console I get the object. I just can't display it on my site because I don't know how to display a state of objects inside a array.
Here is my App.js:
import React, { Component } from "react";
import Paper from "@material-ui/core/Paper";
import Divider from "@material-ui/core/Divider";
const NewsAPI = require("newsapi");
const newsapi = new NewsAPI("APIKEY");
class App extends Component {
constructor() {
super();
this.state = { articles: {} };
newsapi.v2
.topHeadlines({
category: "business",
language: "en",
country: "us"
})
.then(response => {
this.setState({ articles: { response } });
console.log(this.state.articles.response.articles[2]);
});
}
render() {
let article = this.state.articles;
return (
<div>
<div style={{ display: "flex" }}>
<div
style={{ marginLeft: "23em", width: "75%", paddingBottom: "20px" }}
>
<Paper>
<div style={{ textAlign: "center" }}>
<p style={{ margin: "50px" }}>
<b />
</p>
<br />
</div>
<p>
{article.map(articles => (
<p>{articles.name}</p>
))}
</p>
<br />
<Divider />
</Paper>
<div style={{ textAlign: "center", paddingTop: "20px" }} />
</div>
</div>
</div>
);
}
}
export default App;
I currently get the error that map isn't a function.
Response from API:
// Edited: Changed articles from array to object.
// Thanks to everyone... devserkan's answer helped the most and I can now move on with my project!

articlesstate as an array but then in yoursetStateyou are setting it in an object.articlesas an array in your state.