Home > OS >  How to return a div with an image element for each document in a firestore collection
How to return a div with an image element for each document in a firestore collection

Time:12-16

I have a bunch of documents containing links to a bunch of different images in a firestore collection. I would like to display an image on my screen for every document in the collection.

Code: (Mildly fragmented because I don't wanna upload my whole project)

async function DisplayImageData()
{
  const querySnapshot = await getDocs(collection(db, "users", userUID, "images"));
  querySnapshot.forEach((doc) => {
    return(
      <img src={doc.image} />
    );
  });
}

It should be stated that I have actually gotten the get/upload part of this process working, so I know that isn't the problem.

CodePudding user response:

async function DisplayImageData()
{
  const querySnapshot = await getDocs(collection(db, "users", userUID, "images"));
  return <>(querySnapshot.map((doc) => {
    return(
      <img src={doc.image} />
    );
  }))</>;
}

You have to do something like that. Because now the entire list has been returned instead of a single component inside.

CodePudding user response:

To fix your issue, you need to return something like:

<img src={doc.data().image} />

Because the data you want to use is inside the return object of doc.data(). Also you need to use a map instead of a forEach as you can not return something from a forEach function.

  • Related