简体   繁体   中英

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

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

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM