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);
})
Related
I am trying to create a cloud function that stores a file into storage. Oringally I had this on the front-end, but have decieded that I need this done as a cloud function. I am struggling with how to do this. my function looks like:
const functions = require("firebase-functions");
const admin = require("firebase-admin");
exports.exampleFunction = functions.https
.onCall((data, context) => {
const someData = {
some1:"abc",
some2: "def"
};
let newKey;
return admin.database()
.ref("/level1/"+data.dataVar1+"/level2/"+data.dataVar2+"/random")
.push(someData)
.then((snapshot)=>{
newKey=snapshot.key;
return admin.database()
.ref("/level1/"+data.dataVar1+"/level2/"+data.dataVar2)
.once("value");
})
.then((snapshot)=>{
const file = data.file;
//Error here
return admin.storage().ref()
.child(snapshot.val().randomVar+"/"+newKey)
.put(file);
})
.catch((error)=>{
console.log(error);
console.log(error.message);
return error;
});
});
However, when I run this I get the following error:
admin.storage(...).ref is not a function
How can I upload the file to storage?
The storage() method returns an instance of Storage class that does not have a ref() method. You need to get reference to the File and then save() it as shown below:
return admin.storage().bucket() // <-- default bucket
.file(snapshot.val().randomVar + "/" + newKey)
.save(file)
.then(() => {
console.log("File uploaded")
return
})
.catch((e) => console.log(e));
I'm trying to delete an image from Firebase storage in React Native by downloadURL. Also i'm using web V9.
Writing down most essential chuncks of code:
import {
deleteObject,
getStorage,
ref
} from "firebase/storage";
...
// DownloadURL
const photo = "https://firebasestorage.googleapis.com.... ";
const storage = getStorage();
...
const storageRef = ref(storage, photo);
deleteObject(storageRef)
.then(() => {
console.log("File deleted successfully");
})
.catch((error) => {
console.log(error.message);
});
My code is inspired from here and I got this error:
[Unhandled promise rejection: FirebaseError: Firebase Storage: The
operation 'deleteObject' cannot be performed on a root reference,
create a non-root reference using child, such as .child('file.png').
(storage/invalid-root-operation)]
I'm little confused.
Later edit:
My function which upload the image and get the download url:
// uri is returned from "expo-image-picker"
const uploadImageAsync = async (uri) => {
// manipulateAsync imported from 'expo-image-manipulator'
const manipResult = await manipulateAsync(uri, [], {
compress: 0.6,
format: "jpeg",
});
const response = await fetch(manipResult.uri);
const blob = await response.blob();
const imageName = Date.now().toString();
const fileRef = ref(storage, `avatar/${user.uid}/${imageName}.jpg`);
const result = await uploadBytes(fileRef, blob);
getDownloadURL(fileRef).then((snapshot) => {
// downloadURL is added to Redux state to be used later
dispatch(addPhoto(snapshot));
});
};
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);
});
})
I'm using firebase in my react native project.I am saving items and then getting those items in my app. But now I want to edit and delete items based on the key generated by the firebase for each item you can see in the ss.
When I get the data from firebase I'm getting on the items but not the key for each item.So that's why I'm unable to edit or delete items
Kindly help me out on how to do this.
enter image description here
here is my code of add item in the firebase.
export const addMeasurement = params => {
return async dispatch => {
dispatch(measurementLoading());
try {
firebaseService
.database()
.ref('/Measurements')
.push(params)
.then(res => {
measurementAdded(res);
});
} catch (err) {
dispatch(measurementFailed(err));
}
};
};
Here is the code to get items from firebase which was stored early
export const getMeasurements = () => {
return async dispatch => {
dispatch(measurementLoading());
try {
const ref = firebaseService.database().ref('/Measurements');
ref.on('value', snapshot => {
const values = snapshot.val();
if (values !== null) {
const newFreshArr = Object.values(values);
dispatch(measurementSuccess(newFreshArr));
}
});
} catch (err) {
dispatch(measurementFailed(err));
}
};
};
You can get the path of a snapshot like so:
let path = snapshot.ref.path.toString();.
You can then make changes to your Firebase database using that path.
Here’s the documentation on that: https://firebase.google.com/docs/reference/js/firebase.database.DataSnapshot#ref
I'm trying to remove a node from Firebase using cronjob and i have this function but when it gets executed I get an error saying "Error: could not handle the request" and the log says: "database is not defined"
This is my function:
exports.cleanStatsOnRequest = functions.https.onRequest((req, res) => {
const ref1 = firebase.database.ref;
const dbref = ref1.child(`/dailystats`);
console.log('removing dailystats');
return dbref.remove
.then(() => {
res.send('dailystats removed');
})
.catch(error => {
res.send(error);
});
});
What am I doing wrong? What is the right way to define the database?
You need to use the Firebase Admin SDK to access the Realtime Database from an HTTP trigger Cloud Function. This documentation shows you how to read from the database. This example shows writing to the database, which would be similar to deleting.
Try this. database,ref and remove are functions. Read this guide.
Also you should not return dbref.remove() as remove() will return a promise.
exports.cleanStatsOnRequest = functions.https.onRequest((req, res) => {
const ref1 = firebase.database().ref(); // changes here
const dbref = ref1.child('/dailystats');
console.log('removing dailystats');
return dbref.remove() // changes here
.then(() => {
res.send('dailystats removed');
})
.catch(error => {
res.send(error);
});
});