skip to Main Content

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


  1. 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
    
    Login or Signup to reply.
  2. There is possibility that undefined could be the value of testData so rewrite something like this would handle the undefined scenario

    const myData: Item[] = [
        ...(testData ?? []),
        {
          label: 'first',
          value: 'firstValue',
        },
        isVisible && {
          label: 'second',
          value: 'secondValue',
        },
      ];
    
    Login or Signup to reply.
  3. There are a few things to correct:

    1. Conditional Object in array
      It seems you’re trying to insert an object when isVisible is true in myData . To achieve this, you should use the following syntax: ...(isVisable ? [{ label: 'second', value: 'secondValue' }] : [])
    2. Syntax error in jsx
      The myData?.map function’s return block is missing a closing parenthesis for the map callback. Add ) to properly close the map callback

    The corrected code for myData would look like this:

    const myData: Item[] = [
      ...testData,
      {
        label: 'first',
        value: 'firstValue',
      },
      ...(isVisible ? [{ label: 'second', value: 'secondValue' }] : []),
    ];
    

    And the return block:

    return (
      <>
        {myData?.map((item: Item) => (
          <div>
            <div>{item?.label}</div>
            <div>{item?.value}</div>
          </div>
        ))}
      </>
    );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search