I have a forEach() that shows a couple of images. I would like these to be deleted if needed. I fetch the src of the image and the path/file name of the image from Firestore to show with the image on my site (they are uploaded to storage and Firestore).
How do I identify a single image out of all of them and delete just that one?
Js Code
const i = query(collection(db, "teamImages"));
const unsubscribe = onSnapshot(i, (querySnapshot) => {
const teams = document.querySelector('.teamimages');
querySnapshot.forEach((doc) => {
const docData = doc.data();
const article = teams.appendChild(document.createElement('article'));
article.innerHTML = `
<p class="path"></p>
<img class="team-image">
`;
article.children[0].textContent = docData.path;
article.children[1].src = docData.url;
console.log("Current data: ", docData);
});
document.getElementById("team-image").addEventListener("click", function deleteImage() {
const filename = document.getElementById("path").innerHTML;
if (confirm('Are you sure you want to delete this image')) {
const imageDeleteRef = ref(storage, filename);
// Delete the file
deleteObject(imageDeleteRef).then(() => {
// File deleted successfully & delete firestorm reference
deleteDoc(doc(db, teamImage, filename));
}).catch((error) => {
// Uh-oh, an error occurred!
});
} else {
// Do nothing!
console.log('Image not deleted');
};
});
});
The images are in an article section (createElement).
I've had some undefined and null errors when I tried to put in any Firebase delete code.
I'm just not sure how I can define the image filename to use as the reference to delete the file.
The issue looks to be related to how you are setting and getting data for the storage.
You are trying the build the ref using
'const imageDeleteRef = ref(storage, filename);'
From the snippet is not clear what is storage, you could print out the
-storage
-filename
to console to verify that you are fetching proper element.
Here you are setting the data
article.innerHTML = `
<p class="path"></p>
<img class="team-image">
`;
article.children[0].textContent = docData.path;
article.children[1].src = docData.url;
This will produce
<p class="path">docData.path</p>
<img class="team-image" src="{docData.url}">
Then you are trying to get
"const filename = document.getElementById("path").innerHTML;"
You are using https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById where the name is set under class named "path" and possibly you should use
const filename = document.getElementsByClassName("path"),innerHTML;
Or you could change the class to id
from
article.innerHTML = `
<p class="path"></p>
<img class="team-image">
`;
to
article.innerHTML = `
<p id="path"></p>
<img id="team-image">
`;