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
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, withloading..etc..