Reputation: 472
I'm trying to get the name of the file from the result of a promise. So far I can get the actual file url and display it as an audio file but I'm not sure how to get the name of the file. I can only display 0 or 1 from the Object when displaying it in the ul
element.
const fileNames = () =>{
let temp = [];
rootRef.listAll().then( function(res) {
let promises = res.items.map(item => item.getDownloadURL());
Promise.all(promises).then((downloadURLs)=>{
// console.log(downloadURLs)
console.log(res.items)
setFiles(res.items)
setUrls(downloadURLs)
})
// console.log('dsds' + files[0]['name'])
}).catch(function(error) {
// Uh-oh, an error occurred!
});
}
return (
<>
<div>hello {folder}</div>
<ul>
{Object.keys(files).map((file, index) => {
console.log(file)
return <li key={index}> {file}</li>
})}
</ul>
<div>
{urls.map((url, index) => {
return <audio controls key={index} src={url}> {url} </audio>
})}
</div>
</>
)
Here is the console log of the object being returned. As you can see, there is a name
parameter that I'm trying to get with the name of the file being teabeat.mp3
. You can also see at the beginning of the Object array is the 0 that is only being displayed.
Here is the full code:
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
}
// router is getting the current path name
const FolderPage = () => {
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([]);
// Find all the prefixes and items.
const fileNames = () =>{
let temp = [];
rootRef.listAll().then( function(res) {
let promises = res.items.map(item => item.getDownloadURL());
Promise.all(promises).then((downloadURLs)=>{
// console.log(downloadURLs)
console.log(res.items)
setFiles(res.items)
setUrls(downloadURLs)
})
// console.log('dsds' + files[0]['name'])
}).catch(function(error) {
// Uh-oh, an error occurred!
});
}
useEffect(()=>{
fileNames();
},[])
return (
<>
<div>hello {folder}</div>
<ul>
{Object.keys(files).map((file, index) => {
console.log(file.name)
return <li key={index}> {file.name}</li>
})}
</ul>
<div>
{urls.map((url, index) => {
return <audio controls key={index} src={url}> {url} </audio>
})}
</div>
</>
)
}
export default FolderPage
Upvotes: 0
Views: 154
Reputation: 599776
As far as I can tell from looking at the object format in the Storage documentation, you should be able to get the name
property of each object. So:
<li key={index}>{file.name}</li>
Upvotes: 1