Home > OS >  how can I access specific index of array in react js [0]
how can I access specific index of array in react js [0]

Time:11-16

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

CodePudding user response:

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