Home > Back-end >  ReactJs: Uncaught TypeError: Cannot read properties of undefined (reading '0')
ReactJs: Uncaught TypeError: Cannot read properties of undefined (reading '0')

Time:07-09

I am trying to access the key and values in payload in my JSON data, and if the key is present in array, countTargetOptions, I will display it in a component.

But I keep getting a Uncaught TypeError: Cannot read properties of undefined (reading '0') when I try to display the data {payload[0]?.payload?.countTargetOptions[i]} (note: I added the ? after reading enter image description here

CodePudding user response:

You probably wanted to do this:

{targetOption} : {payload[0].payload[countTargetOptions[i]]

About ?.

?. is an operator that returns undefined if the left-hand side is undefined. You added it in the wrong places. Doing this:

{targetOption} : {payload[0].payload.countTargetOptions?.[i]}

would be a little bit better, because you wouldn't get the error then, although the value would still be undefined.

  • Related