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>
)
CodePudding user response:
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);
});