I am trying to iterate the data but it saying testData is not iterable.
This is my code –
const testData = details?.[0]?.one?.map((item) => {
const labelTwo =
item?.itemType === 'FIRST' ? 'newLabel' : 'oldLabel';
return {
label: details?.[0]?.one?.length > 1 ? labelTwo : 'labelOne',
value: item?.value,
};
});
const myData: Item[] = [
...testData,
{
label: 'first',
value: 'firstValue',
},
isVisible && {
label: 'second',
value: 'secondValue',
},
];
return (
<>
{myData?.map((item: Item) => {
return (
<div>
<div>{item?.label}</div>
<div>{item?.value}</div>
</div>
);
}
</>
)
Below in return when I am trying to iterate myData using map function then it is saying testData is not iterable.
Am I doing anything wrong ? what will be the best approach here to iterate the data
>Solution :
As @cmgchess mentioned, the error "testData is not iterable" happens because you are trying to spread an object that is not iterable.
Looking at your code, the most likely cause is that testData is undefined.
Try this:
const testData = details?.[0]?.one?.map((item) => {
const labelTwo = item?.itemType === 'FIRST' ? 'newLabel' : 'oldLabel';
return {
label: details?.[0]?.one?.length > 1 ? labelTwo : 'labelOne',
value: item?.value,
};
}) || []; // Default to empty array if undefined