1

I am developing a React web app with a Firestore database and am trying to download multiple images from Firebase storage with StorageRef and getDownloadURL(). I want to assign the images URLs as a prop to doc but it doesn't work. Does anyone know what I am doing wrong?

function useDishes() {
  const [dishes, setDishes] = useState([])

  useEffect(() => {
    firebase
      .firestore()
      .collection('dishes')
      .onSnapshot(snapshot => {
        const storage = firebase.storage()
        const storageRef = storage.ref()
        const newDish = snapshot.docs.map(doc => ({
          id: doc.id,
          ...doc.data(),
          getDownloadURLs: storageRef
            .child(doc.data().imageString)
            .getDownloadURL()
            .then(url => {
              console.log(url)
              console.log(doc.data())
              //assign url as prop to doc
              return url
            }),
        }))
        setDishes(newDish)
      })
  }, [])

  return dishes
}
skyboyer
  • 22,209
  • 7
  • 57
  • 64
SabSch
  • 13
  • 3

1 Answers1

1

Since getDownloadURL is also an asynchronous call, you'll need to call setDishes in its callback.

firebase
  .firestore()
  .collection('dishes')
  .onSnapshot(snapshot => {
    const storage = firebase.storage()
    const storageRef = storage.ref()
    const promises = snapshot.docs.map(doc => storageRef.child(doc.data().imageString).getDownloadURL());
    Promise.all(promises).then(downloadURLs => {
      const newDish = snapshot.docs.map((doc, index) => ({
        id: doc.id,
        ...doc.data(),
        getDownloadURLs: downloadURLs[index]
      }))
      setDishes(newDish)
    })
  })
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807