简体   繁体   中英

How to View All Images from a firebase storage bucket folder in reactJS

I want to view all uploaded images from a specific folder in my firebase storage bucket.

I managed to get the list of all the URLs in the folder, but when I try to view them, only one image shows, and the rest are not being shown.

What am I doing wrong?

Here is my code:

const [allRandomImages,setAllRandomImages] = useState([])
const images = []


const getRandomImages = () => {

    const storageRef = storage.ref(`random/${AWB}`)

    storageRef.listAll().then((result) => {
      result.items.forEach((imageRef) => {
        imageRef.getDownloadURL().then((url) => {
          console.log(url);
          images.push(url)
          setAllRandomImages(images)
        })
       
      }) 
      
    })       
  }

    useEffect(() => {
      getRandomImages()
    },[]);

return (
         <div>
                
            <a><img id="packing"  alt="" style={styles}  /></a>
            <a><img id="commercial"  alt="" style={styles} /></a>
            <a><img id="cof"  alt="" style={styles} /></a>
            <a><img id="otherdoc"  alt="" style={styles} /></a>
            
              
                  { allRandomImages.map((img, i) => (
                    <img src={img} />
                  ))}
             
         </div>
)

Since you want to execute, in parallel , an undetermined number of calls to the asynchronous getDownloadURL() method, you can use Promise.all() as follows (untested):

storageRef.listAll()
.then((result) => {
   const promises = [];
   result.items.forEach((imageRef) => {
     promises.push(imageRef.getDownloadURL());
   });
   return Promise.all(promises);
 })
 .then(urlsArray => {
    setAllRandomImages(urlsArray);
 });
  

You can also use map , as follows:

storageRef.listAll()
.then((result) => {
   return Promise.all(result.items.map(imageRef => imageRef.getDownloadURL());
 })
 .then(urlsArray => {
    setAllRandomImages(urlsArray);
 });

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