list all files in firebase storage v9 - javascript

I am developing a page and am using firebase storage as the file storage. I tried using the given codes in the firebase developer docs but I can't seem to make it work. What could be the problem?
document.getElementById("but").addEventListener('click', e => {
// Create a reference under which you want to list
const listRef = ref(storage, 'folder/');
// Find all the prefixes and items.
listAll(listRef)
.then((res) => {
res.prefixes.forEach((folderRef) => {
// All the prefixes under listRef.
// You may call listAll() recursively on them.
});
res.items.forEach((itemRef) => {
// All the items under listRef.
console.log( getDownloadURL(ref(storage, `folder/${itemRef}`)))
})
})
});

I'm not sure what problem you have with the code, but one mistake is in :
res.items.forEach((itemRef) => {
// All the items under listRef.
console.log( getDownloadURL(ref(storage, `folder/${itemRef}`)))
})
The getDownloadURL function performs an asynchronous call to the server, so you'll need to either use await or then to capture that result:
res.items.forEach((itemRef) => {
getDownloadURL(ref(storage, `folder/${itemRef}`))
.then((downloadURL) => {
console.log(downloadURL);
});
})

Related

firebase onSnapshot not updating data in real time

I'm learning firebase and I'm baffled because I'm following the tutorial to the dot, literally copy and paste and though the following code:
// init firebase
initializeApp(firebaseConfig)
// init services
const db = getFirestore()
// collection ref
const colRef = collection(db, 'books')
// real time collection data
onSnapshot(colRef, (snapshot) => {
let books = []
snapshot.docs.forEach(doc => {
books.push({ ...doc.data(), id: doc.id })
})
console.log(books)
})
// adding docs
const addBookForm = document.querySelector('.add')
addBookForm.addEventListener('submit', (e) => {
e.preventDefault()
addDoc(colRef, {
title: addBookForm.title.value,
author: addBookForm.author.value,
})
.then(() => {
addBookForm.reset()
})
})
in the tutorial results in data being updated live (changes are reflected in the console, as users add/removes books), on my app changes are reflected only after refreshing the page.
I did some digging but only managed to find people with similar issue but no answer, i tried changing snapshot.docs.forEach(doc => ...) to snapshot.docChanges().forEach(doc => ...). same result.

How can I remove an entire folder under Storage?

I have a problem deleting my entire folder on firebase storage. I always get a 'storageRef.listAll is not a function' error when I specify the reference to the path. I would like to delete the complete path with all possibly existing images.
const storage = getStorage();
const storageRef = ref(
storage,
`${aktuellerUser._id}/artikelBilder/`
);
storageRef
.listAll()
.then((listResults) => {
const promises = listResults.items.map((item) => {
return item.delete();
});
Promise.all(promises);
})
.catch((error) => {
console.log(error);
});
error TypeError: storageRef.listAll is not a function
You are using the new Firebase Modular SDK where listAll() is a top level function and not a method on StorageReference. Similarly, you need to use deleteObject() to delete a file now instead of .delete() method as shown below:
import {
getStorage,
ref,
listAll,
deleteObject
} from "firebase/storage";
listAll(storageRef)
.then(async (listResults) => {
const promises = listResults.items.map((item) => {
return deleteObject(item);
});
await Promise.all(promises);
})

Reading a value from Realtime Firebase

I have the following json structure:
Within "all" node I have an attribute "drinkId" and I'm trying to move it outside that child node bringing it one level up.
I'm trying to read the value without any luck
const cocktailRef= firebase
.database()
.ref("Ratings");
cocktailRef.once("value", (snapshot) => {
snapshot.forEach((child) => {
const drinkIdPass = child.ref.child("all").child("drinkId").value();
child.ref.update({ drinkId: drinkIdPass });
})
})
I've tried different variants of ".value()", same problem
There isn't any value() method on a DataSnapshot. It's val() Try refactoring your code like this:
const cocktailRef= firebase.database().ref("Ratings");
cocktailRef.once("value").then(async (snapshot) => {
const updates = { }
snapshot.forEach((child) => {
const drinkIdPass = child.val().all.drinkId
updates[`${child.key}/drinkId`] = drinkIdPass
})
await cocktailRef.update(updates)
console.log("Data updated")
})

React Firebase Snapshot retrieve all children

So I've been scratching my head for a while now over a function that I can't seem to make work in React. I'm creating this basic file manager with the Firebase storage and the Cloud Firestore.
What I'm trying to do is to fetch all children in "files", but in this very process also run a function within the fetching process grabbing the file uploaders name and then push it to my array so I can display the file list with correct information instead of showing an id of the file owner. This is the code that I have so far:
export const retrieveLibrary = () => {
return new Promise((resolve, reject) => {
fetchCompanyId().then((companyId) => {
var allFiles = [];
database.collection("files").orderBy("uploadDate").get().then((snapshot) => {
if(!snapshot.empty){
snapshot.forEach((singleSnapshot) => {
fetchFileOwner(singleSnapshot.data().owner).then((name) => {
allFiles.push({key: singleSnapshot.id, downloadLink: singleSnapshot.data().downloadLink, name: singleSnapshot.data().name, type: singleSnapshot.data().type, uploadDate: singleSnapshot.data().uploadDate, password: singleSnapshot.data().password ? true:false, owner: name});
})
})
resolve(Promise.all(allFiles));
}
}).catch((e) => {
reject(e);
})
})
})
}
Here I'm basically doing everything connected with Firebase and trying to create an array that I can retrieve from a promise.
export const fetchFileOwner = id => {
return new Promise((resolve, reject) => {
database.collection("users").doc(id).get().then((userInfo) => {
resolve(userInfo.data().firstName);
}).catch((e) => {
reject(e);
})
})
}
Pretty simple, grabbing the users first name.
fetchLibraryFiles().then((library) => {
setLibraryFiles(library);
}).catch((e) => {
console.log(e);
})
This is the function I'm calling to retrieve the full library. As you can probably see, I have tried my best to find a way to do this, but I am not able to retrieve the full array. However, when I remove the fetchFileOwner function call inside retrieveLibrary - it works. What am I doing wrong here and why is it wrong? What is the best way of doing something like this where I have to call other functions and wait for the data retrieved?
Help is greatly appreciated.
Data format is here:
the owner is just a UID tied to an account.

firebase set/initialize values to zero dynamically

I'm looking a good and right way to set/ initalize values with http trigger.
what I did is ref to the node in firebase and get data then update it.
module.exports.initializeAnswers = functions.https.onRequest(async(req,res)=>{
try{
// i want to initalize each key
await firebase.ref('/CurrentGame').once('value',snapshot=>{
snapshot.forEach((childSnapshot)=>{
if(childSnapshot !=null){
childSnapshot.update(0)
}
return false
});
})
}catch(e){
console.info(e)
return res.status(400).send({error:0})
}
})
I'm looking for a right way and not by the 'update' function
I want to initalize each value to zero with http trigger
I understand that you will have several children (variable number) under the "answers" node and only one "rightAnswer" node. If my understanding is correct, the following code will do the trick:
exports.initializeAnswers = functions.https.onRequest((req, res) => {
admin.database().ref('/CurrentGame/answers').once('value', snapshot => {
const updates = {};
snapshot.forEach((child) => {
updates['/answers/' + child.key] = 0;
});
updates['/rightAnswer'] = 0;
return admin.database().ref('/CurrentGame').update(updates);
}).then(() => {
res.status(200).end();
}).catch((err) => {
console.log(err);
res.status(500).send(err);
});
});
You can use Firebase Cloud Functions to initialize the values on HTTP trigger. check this link

Categories

Resources