Home > OS >  Firebase Storage listAll() together with getDownloadURL() doesn't work out
Firebase Storage listAll() together with getDownloadURL() doesn't work out

Time:09-10

In utils file I wrote a function that collects all the urls of images located inside a folder in Firebase Storage with the path "proj_name/screenshots/uid/" (there are 8 imgs) and import it inside Next.js [id] page using getServerSideProps(). However when I console.log the length of array with the urls it always outputs 0. What may cause this problem?

Utils file:

...
export const getImages = async (dir) => {
  let data = []
  const storage = getStorage()
  const listRef = ref(storage, dir)
  await listAll(listRef)
    .then(res => {
      res.items.forEach(itemRef => {
        getDownloadURL(itemRef)
          .then(url => {
            data.push(url)
          })
      })
    })
  return data
}

Next.js page file:

import { getItems, getImages } from "../../utils/firebase"



export const getServerSideProps = async (context) => {
  const id = context.params.id
  const item = await getItems(id)
  const screenshots_urls = await getImages('proj_name/screenshots/'   id)
  return{
    props: { item, screenshots_urls }
  }
}



const Details = ({ item, screenshots_urls }) => {
  return (
    <>
      {
        console.log(screenshots_urls.length)
      }
    </>
  )
}
 
export default Details

CodePudding user response:

I would recommend using either async-await or promise chaining only and not both. Try refactoring the code as shown below:

export const getImages = async (dir) => {
  let data = []
  const storage = getStorage()
  const listRef = ref(storage, dir)
  const res = await listAll(listRef)

  const promises = res.items.map((itemRef) => getDownloadURL(itemRef))
  const data = await Promise.all(promises)
  console.log(data)

  return data
}
  • Related