0
constructor(props){
  super(props);

  this.state = {
      posts: [],
  }
}

componentWillMount() {
  fetch("https://newsapi.org/v2/top-headlines?country=us&apiKey=${API_KEY}")
      .then(res => res.json())
      .then(data => this.setState({posts:data}));
}

render() {
  return (
    <div>
      <ul>
        { this.state.posts.map(post => <li key={post.id}>{post.title}</li>) }
      </ul>
    </div>
  )
}

I'm trying to map the title of this news object but whenever i try to do that I get this error: TypeError: this.state.posts.map is not a function. This is the picture of the object from data : https://i.stack.imgur.com/3fnlg.png

asynts
  • 2,213
  • 2
  • 21
  • 35
rockwire
  • 95
  • 1
  • 9
  • 2
    do `console.log(data)` to see what is contains.. I am sure as per your error, `data` is not an array. – Arup Rakshit Oct 13 '18 at 17:37
  • Here's the pic of data : https://i.imgur.com/ctvXXWA.png – rockwire Oct 13 '18 at 17:42
  • @arup and per the question title "How do I map over an object", `data` is not an array either. – Jonas Wilms Oct 13 '18 at 17:48
  • In the picture, the data is an array named articles, not an object named posts?? – Jonas Høgh Oct 13 '18 at 17:49
  • the posts is just a state which contains the data. – rockwire Oct 13 '18 at 17:49
  • Here is the answer to your problem [https://stackoverflow.com/a/50486586/7878987](https://stackoverflow.com/a/50486586/7878987) – Daggie Blanqx - Douglas Mwangi Oct 13 '18 at 18:07
  • @JonasWilms The OP thought, OPs use of `.map` is buggy, which is not. The OP assumed state has an array already, so why the map is not working. And there the OP has the mistake **the assumption**. The OP wants or knows the endpoints is going to give an array, because `posts: [],` .. I am aware of `data` is not array either. that is why I asked the OP to see what it looks like using `console.log()` so that the OP figures out by yourself it is map problem, rather datastrucure problem. – Arup Rakshit Oct 13 '18 at 18:35
  • @JonasWilms Also your dup question mark to close the question doesn't makes sense to me. anyway it is your call.. – Arup Rakshit Oct 13 '18 at 18:37
  • @rockwire Is your problem solved? – Arup Rakshit Oct 14 '18 at 13:28
  • The solution was in the setstate posts:data.articles – rockwire Oct 14 '18 at 13:47

1 Answers1

3

Return an array of the object's using Object.keys()

{Object.keys(posts).map((item, i) => (
       <li key={i}>{posts[item].title}</li>
))}
user-9725874
  • 831
  • 9
  • 15