Home > Mobile >  Loading result of a useState Array
Loading result of a useState Array

Time:10-11

I have a useState initialized with default value.

I'm trying to loop through it and display a list of cards. If i try to add a card manually it works, but using map or foreach doesn't seem to loop through the initial list

function App() {
  const [raffles, setRaffles] = useState<Raffle[]>([new Raffle("Raffle 1")])

  return (
    <div className="App">
      {
        raffles.map(raffle => {
          <RaffleCard 
            name = {raffle.name}
            callback = {joinRaffle} />
        })
      }
    </div>
  );
}

export default App;

class Raffle {
  name: string

  constructor(name: string) {
    this.name = name
  }
}

CodePudding user response:

You are forgetting to return the JSX in your mapping function.

function App() {
  const [raffles, setRaffles] = useState<Raffle[]>([new Raffle("Raffle 1")])

  return (
    <div className="App">
      {
        raffles.map((raffle, index) => {
          return <RaffleCard key={index}
            name = {raffle.name}
            callback = {joinRaffle} />
        })
      }
    </div>
  );
}

export default App;

class Raffle {
  name: string

  constructor(name: string) {
    this.name = name
  }
}

Also, the map function gives you access to the index of the array you're iterating. React might complain if you dont assign a key to your objects. Add key={index} to each Raffle object.

  • Related