Home > Back-end >  How to Delete Image from Firebase cloud Storage - REACT
How to Delete Image from Firebase cloud Storage - REACT

Time:01-10

I have the following structure in my Storage, Post/ID/image.jpg . Post and ID are folders that can be found easily but ID may contain multiple images. How could I possibly delete all of them ? Inside my code, I have a function that should delete Posts inside firestore database and delete the images reference from the firebase storage

The error thrown is :

TypeError: Cannot read properties of undefined (reading '_throwIfRoot')

Delete Function

const DeletePost = async (e) => {
    e.preventDefault();
    const querySnapshot = await getDocs(collection(db, `${category}Posts`));
    querySnapshot.forEach((docx) => {
        if (post.AdTitle === docx.data().AdTitle) {
            try {
                deleteObject(ref(storage, `${category}Posts`, docx.id).child);
                deleteDoc(doc(db, `${category}Posts`, docx.id));
            } catch (error) {
                console.log("error in delete image, "   error);
            }
            // router.reload();
        }
    });
};

EDIT

The post folder the images to be deleted Content of Docx.id

CodePudding user response:

There isn't any child property on a StorageReference. Try removing it as shown below:

deleteObject(ref(storage, `${category}Posts`, docx.id   ".ext")) // .child);

// Make sure you add the file extension at the end

Also both deleteObject() and deleteDoc return a promise, so do checkout: Using async/await with a forEach loop

CodePudding user response:

Following this documentation I finally came up with a working solution and here's the updated code.

try {
    const listRef = ref(storage, `${category}Posts/${docx.id}/`);
    listAll(listRef)
      .then((res) => {
        res.items.forEach((itemRef) => {
          setValues((prevState) => [...prevState, itemRef]);
        });
        if (values !== "") {
          console.log("attempting");
          values?.map((value) =>
            deleteObject(
              ref(storage, `${category}Posts/${docx.id}/${value.name}`)
            ).then(() => {
              console.log("storage success");
            })
          );

          deleteDoc(doc(db, `${category}Posts`, docx.id)).then(() => {
            console.log("doc success");
            router.reload();
          });
        }
      })
      .catch((error) => {
        console.log("error : "   error);
      })
  •  Tags:  
  • Related