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
3
Answers
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:
There is possibility that undefined could be the value of
testData
so rewrite something like this would handle the undefined scenarioThere are a few things to correct:
It seems you’re trying to insert an object when
isVisible
is true inmyData
. To achieve this, you should use the following syntax:...(isVisable ? [{ label: 'second', value: 'secondValue' }] : [])
The
myData?.map
function’sreturn
block is missing a closing parenthesis for the map callback. Add)
to properly close the map callbackThe corrected code for
myData
would look like this:And the return block: