0

I am trying to render the data returned from a graphql query but I am getting the error TypeError: Cannot read property 'map' of undefined

If I log the data to the console, I am able to see that it was returned successfully:

{listTalks: Array(100)}
    listTalks: Array(100)
        [0...99]
            0: {ID: "xxxxxxxy", speakerName: "Bob", name: "Talk1", description: "text"}
            1: {ID: "xxxxxxyy", speakerName: "Joe", name: "Talk2", description: "text"}
            2: {ID: "xxxxxyyy", speakerName: "Carry", name: "Talk3", description: "text"}
            3: {ID: "xxxxyyyy", speakerName: "Kyle", name: "Talk4", description: "text"}
            4: {ID: "xxxyyyyy", speakerName: "Mark", name: "Talk5", description: "text"}

However when I map the data to try and render it, the error appears.

Full code below:

class App extends React.Component {

  // define some state to hold the data returned from the API
  state = {
    talks: []
  }

  // execute the query in componentDidMount
  async componentDidMount() {
    try {
      const talkData = await client.query({query: gql(listTalks)})
      console.log('talkData:', talkData)
      this.setState({
        talks: talkData.data.listTalks.items
      })
    } catch (err) {
      console.log('error fetching talks...', err)
    }
  }


  render() {
    return (
      <>
      <div>
        {
           this.state.talks.map((talk, index) => (
            <div key={index}>
              <h3>{talk.speakerName}</h3>
              <h5>{talk.name}</h5>
              <p>{talk.description}</p>
            </div>
          ))

        }
        </div>
      </>
    )
  }
}

export default App
1
  • Your data is async, so you need to check if the data has arrived,. simply place if (!this.states.talks) return null; as the first line of your render, the second render when you actually have the data, state.talks will exist. You could also replace null, with loading.. etc.. Commented Dec 17, 2020 at 20:17

1 Answer 1

1

I think talkData.data.listTalks.items is equal to undefined and because of that it throws undefined.map is not a function.

this.setState({
    talks: talkData.data.listTalks
  })

Maybe it happens because of that .items property.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.