Myka
Myka

Reputation: 77

can't access array of objects in object

I'm baffled about why I'm getting an error when trying to access an array inside of an object in ReactJS.

I am using Redux to store an object in State.

I have a success function that allows the page to render, so by the time I get to this object it has for sure loaded. (I noticed a ton of similar questions to this where that's usually the problem).

When I do this I get the proper results:

const { events } = this.props
console.log(JSON.stringify(events.listSignup))

{"data":[{"eventID":"264712106049274377","name":"BookOne","email":null,"verify":null,"privacy":null,"order":null,"group":null},{"eventID":"264712106049274377","name":"BookTwo","email":null,"verify":null,"privacy":null,"order":null,"group":null}]}

I can see that the array "data" exists, but when I try:

    console.log(JSON.stringify(events.listSignup.data[0].name))

or

    console.log(JSON.stringify(events.listSignup.data[0]))

I get "TypeError: Cannot read property 'data' of undefined"

I'm at my wits end trying to figure out what's going on. Any advice would be much appreciated!

Upvotes: 0

Views: 1596

Answers (1)

Ed_
Ed_

Reputation: 19098

You're right to be baffled, because what you [think you] have observed isn't possible.

This happens a lot to me as a developer, and my advice is that when this happens, trust your knowledge (you know this isn't possible!) and double check what you are seeing.

I suspect that the first time your component renders, this.props.events is undefined, but then it very quickly re-renders with this.props.events being set.

I would suggest adding back this line (without the others):

console.log(JSON.stringify(events.listSignup))

And scrolling up in your javascript console to see if you have any logs that are just displaying undefined. If so, you probably need to double check the logic which is preventing the page from rendering before you have successfully received the data, as I suspect that is where your problem is.

Upvotes: 1

Related Questions