-2

On calling an API , got a response, stored it in a variable "items" and it is getting displayed on console also. When i access items.data[0].id, it is getting displayed in console but when i try to display same thing in render method, error is coming that :-

TypeError : cannot read property 0 of undefined.

I am calling the API call in ComponentWillMount() function in react.

rockz
  • 121
  • 1
  • 11

1 Answers1

0

I don't think there is enough context here to answer your question. Can you provide an example? In the meantime, I'll still try to help you.

I am not sure if your request is synchronous or asynchronous. Looking at your error, you are probably making an asynchronous request. When the first render() is called, items hasn't resolved yet. Therefore, item.data is undefined, which is the cause of your error.

A solution is to initialize the data property of this.state.item to an empty array [], that way your not calling the index operator of an undefined object.

Nigel Gilbert
  • 439
  • 5
  • 5