Firebase Storage : How to check image is exist or not in my Storage? (React JS)

Viewed 72

My function is working fine when an image exists, in my case when I triggered the delete function image might not exist. when the image does not exist I am getting an error. ( DELETE https://firebasestorage.googleapis.com/v0/b/anayase-dc577.appspot.com/o/userimages%2Fcustomerimage%2Fa%20(2).jpg 404)

function DeleteImage(path, imgname) {
    const storage = getStorage();
    // Create a reference to the file to delete
    const imageRef = ref(storage, path + '/' + imgname);
    console.log(imageRef)
    // Delete the file

    deleteObject(imageRef).then(() => {
        console.log("File Deleted Successfully")
    }).catch((error) => {
     console.log(error)
    });

}
1 Answers

You could use a simple if else for this. Check if the imageRef is null, or whether it's having a null prop. Based on that, you can perform the delete operation.

for an example,

if(imageRef !== null){
 deleteObject(imageRef).then(() => {
        console.log("File Deleted Successfully")
    }).catch((error) => {
     console.log(error)
    });
}

or,

if(imageRef.prop !== null){
     deleteObject(imageRef).then(() => {
            console.log("File Deleted Successfully")
        }).catch((error) => {
         console.log(error)
        });
    }

note that prop is a property that is in the imageRef object.

Related