I'm getting the list of all the file names in a directory and then I want to get the download urls and do a foreach loop to get them. My issue is the tempUrls is empty and I can't set the state of urls
import React, { useState, useEffect, useRef } from 'react';
import firebase from "firebase/app";
import storage from "firebase/storage";
import firebaseConfig from "../dropzone/config";
import {
BrowserRouter as Router,
Switch,
Route,
Link,
useRouteMatch,
BrowserRouter,
useParams
} from "react-router-dom";
if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig);
}else {
firebase.app(); // if already initialized, use that one
}
const FolderPage = () => {
// router is getting the current path name
let {folder} = useParams();
let fb_storage = firebase.storage();
let storageRef = fb_storage.ref();
let rootRef = storageRef.child(folder);
console.log(rootRef);
const [files, setFiles] = useState([]);
const [urls, setUrls] = useState([]);
const fileNames = () =>{
rootRef.listAll().then(function(res) {
let temp = [];
res.prefixes.forEach(function(folderRef) {
// console.log(folderRef.name)
// All the prefixes under listRef.
// You may call listAll() recursively on them.
});
res.items.forEach(function(itemRef) {
// All the items under listRef.
temp.push(itemRef.name)
console.log(itemRef.name);
});
setFiles(temp);
}).catch(function(error) {
// Uh-oh, an error occurred!
});
let tempUrls = [];
files.forEach(function(file){
var fileRef = storageRef.child( folder + '/' + file);
// Get the download URL
fileRef.getDownloadURL()
.then((url) => {
tempUrls.push(url);
console.log(tempUrls)
})
.catch((error) => {
// A full list of error codes is available at
// https://firebase.google.com/docs/storage/web/handle-errors
switch (error.code) {
case 'storage/object-not-found':
// File doesn't exist
break;
case 'storage/unauthorized':
// User doesn't have permission to access the object
break;
case 'storage/canceled':
// User canceled the upload
break;
// ...
case 'storage/unknown':
// Unknown error occurred, inspect the server response
break;
}
});
})
}
useEffect(()=>{
fileNames();
},[])
return (
<>
<div>hello {folder}</div>
{/* <div>hello {folders}</div> */}
<ul>
{files.map((file, index) => {
return <li key={index}> {file}</li>
})}
</ul>
<div>
{urls.map((url, index) => {
return <a key={index} href={url}> {url} </a>
})}
</div>
</>
)
}
export default FolderPage