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 React: Uncaught TypeError: Cannot read properties of undefined (reading '0') but it is still not working).
Before I tried to render the components in a loop, there was no issues. See below my code and a photo of the payload data.
const countTargetOptions = [
"count_targets",
"count_targets_excluded",
"count_targets_pending",
"count_targets_in_progress",
"count_targets_completed",
"count_targets_failed",
];
const CustomTooltip = ({ payload}: TooltipProps<ValueType, NameType> | any) => {
if( payload && payload.length){
var targetsData = [];
let payloadData: any = payload[0].payload;
for(let i = 0; i < countTargetOptions.length; i++){
if(payloadData.hasOwnProperty(countTargetOptions[i])){
let targetOption: string = countTargetOptions[i].replaceAll('_', ' ');
targetsData.push(
<Typography key = {targetOption} sx={{ fontSize: 14 }} color={"black"} >
{targetOption} : {payload[0]?.payload?.countTargetOptions[i]}
</Typography> )
}
}
return (
<>
<Card>
<CardContent>
{targetsData}
//Example of what wored before loop
{/* <Typography sx={{ fontSize: 14 }} color={"black"} >
count targets : {payload[0].payload.count_targets}
</Typography> */}
</CardContent>
</Card>
</>
);
}
return null;
}
>Solution :
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.
