Returning iterations with React-Native

Viewed 28

I've been using React not too long, but I keep running into this issue while trying to avoid it every time.

Upon iterating through my forloop, it gives me two different iterations, as expected.

Output:

{name: "Sensor 1", type: "Airsensor"}

{name: "Sensor 2", type: "Watersensor"}

However, my code seems to be only using the second iteration.

Output on screen:

{name: "Sensor 2", type: "Watersensor"}

{name: "Sensor 2", type: "Watersensor"}

The code in question is:

export default function SensorCards() {
  let allCards = [
    {name: 'Sensor 1', type: 'Airsensor'},
    {name: 'Sensor 2', type: 'Watersensor'},
  ];

  for (let i = 0; i < allCards.length; i++) {
    var cardsOnScreen = allCards.map(function (card) {
      return <Card name={allCards[i].name} type={allCards[i].type} />;
    });
  }
  return cardsOnScreen;
}

I keep trying to change the return to something else, because I think my issue lays there, however I can't seem to find an alternative for my situation. My return keeps only returning the last object x times in objects.

Thanks in advance!

2 Answers

Replace this:

  for (let i = 0; i < allCards.length; i++) {
    var cardsOnScreen = allCards.map(function (card) {
      return <Card name={allCards[i].name} type={allCards[i].type} />;
    });
  }
  return cardsOnScreen;

with this:

    return allCards.map((card) => (
      <Card key={card.name} name={card.name} type={card.type} />
    ));

The problem in your code are:

  1. You are looping twice, you don't need to.
  2. You are resetting cardOnScreen in the inner loop
  3. You are not setting key when looping

Try this:

export default function SensorCards() {
  let allCards = [
    {name: 'Sensor 1', type: 'Airsensor'},
    {name: 'Sensor 2', type: 'Watersensor'},
  ];
  return (
     <>
       { allCards.map((card) => (
      <Card key={card.name} name={card.name} type={card.type} />
       ))}
     </>
  )
}
Related