Jocodes
Jocodes

Reputation: 21

I keep getting this TypeError: Cannot read property 'map' of undefined

I am trying to render this data from the API onto my page. I am aware that what I am trying to render isn't in the typical array its a javascript object which is throwing me off. With my code, as is, the API data is there its just a matter of being able to access because .map isn't working because the data I have is not an array. Do I need to create another function?

I am not sure

import React from 'react';
import './App.css';

class App extends React.Component {
 
  state = {
  apiData: []
  }
 
  render() {   
    
  console.log('api datat is')

    return (
      <div>
        <center>
        <h1>hello something</h1></center>
        {this.state.apiData.map(title => title.rendered)}
      </div>
    )
  }
 
  componentDidMount() {
    fetch('http://www.mocky.io/v2/5dece3d333000052002b9037')
      .then(response => response.json())
      .then(data => {
        this.setState({
          apiData: data.data
        })
      })        
      console.log("component fetched data")
  }
}
 
export default App

Any help would be great.

I am still learning how to code so be nice

Upvotes: 0

Views: 433

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370749

Look at the API response:

{
  "id": 233383,
  "date": "2019-10-28T10:50:53",
  "date_gmt": "2019-10-28T10:50:53",
  "modified": "2019-10-28T10:55:14",
  "modified_gmt": "2019-10-28T10:55:14",
  "link": "https:\/\/www.stylist.co.uk\/long-reads\/friendship-friends-whatsapp-facebook-messenger-social-media-group-chat-best-friends-psychology-advice\/233383",
  "title": {
    "rendered": "Whatsapp and Facebook Messenger: how group chat is changing the dynamic of our friendships"
  },
  "slug": "whatsapp-and-facebook-messenger-how-group-chat-is-changing-the-dynamic-of-our-friendships",

etc.

It does not have a .data property, so

  .then(data => {
    this.setState({
      apiData: data.data
    })
  }) 

sets undefined to this.state.apiData.

The only rendered exists in the one top-level object in the response, so you should remove the .map entirely, something like:

  .then(data => {
    this.setState({
      apiData: data
    })
  })  
<h1>hello something</h1></center>
{this.state.apiData.title.rendered}

Upvotes: 1

Related Questions