cannot read properties of undefined // access specific index of array in react js [0]

Viewed 2163

this code works

the code works fine but when I try to access the first index it says "cannot read properties of undefined (reading '0')"

this code doesn't work

this is the response of console.log("Dataa", this.state.data.videos)

response

this is the response of console.log("Dataa", this.state.data.videos[0])

enter image description here

1 Answers

This is because you are trying to get an index of undefined. Before setting the state to data, the state key 'videos' is undefined. You can try in render:

if (this.state.data.videos) {
  console.log('Data', this.state.data.videos[0])
}
Related