'Trying to loop through firebase and display each object as a card React

My data is structured like so [1]: https://i.stack.imgur.com/dWsr3.png

I am trying to loop through the database and put the data from each card into props for my ProductCard> component. It takes in values as I've been racking my brain with this and googling constantly, but this is my best attempt.

const db = getDatabase();
const dbRef = ref(db, 'products');
onValue(dbRef, (snapshot) => {
    snapshot.forEach((childSnapshot) => {
      return (
          <ProductCard title={childSnapshot.val().prod_title} />
      )
    });
  }, {
    onlyOnce: true
  });

I'm very much a noob with react so I appreciate any advice!



Solution 1:[1]

Use map function instead of forEach to return an array of JSX elements, and then do something with this elements array (not sure what, since your snippet is too small):

const elements = snapshot.map((childSnapshot) => {
  return (
      <ProductCard title={childSnapshot.val().prod_title} />
  )
});
// do something with elements array here or maybe just return it

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Adrian Schweizer