Wednesday, 6 July 2022

How to remove images from Firebase Storage?

I'm trying to adapt a React Native project to the new Firebase methods. In it I upload images to Storage and they are added to the App interface. I can also remove these images from the interface as shown in the following code:

const removeImage = (img) => { // delete an image selected by the user
    Alert.alert(
      "Eliminar imagen",
      "¿Estás seguro de eliminar esta imagen?",
      [
        {
          text: "Cancelar",
          style: "cancel",
        },
        {
          text: "Eliminar",
          onPress: () => {
            const result = filter(
              formik.values.images,
              (image) => image !== img
            )
            formik.setFieldValue("images", result)
          },
        },
      ],
      { cancelable: false }
   

 ) 
  }

The problem is that in this way, they are only removed from my App, while the images are still stored in Firebase. My idea is that when I remove the images from the frontend, they will also be removed from the Firebase Storage.

I have read Firebase documentation, and this would be possible with the deleteObject function

const storage = getStorage();

// Create a reference to the file to delete
const desertRef = ref(storage, 'images/desert.jpg');

// Delete the file
deleteObject(desertRef).then(() => {
  // File deleted successfully
}).catch((error) => {
  // Uh-oh, an error occurred!
})

I did some test, and I can't get it to work. I don't know exactly how I should add the Firebase instructions shown here.

How should I implement this function in my code to remove images from Storage?

Thank you

import { getStorage, ref, deleteObject,  uploadBytes, getDownloadURL } from "firebase/storage"
export function UploadImagesForm(props) {
  const { formik } = props
  const [isLoading, setIsLoading] = useState(false) // status for loading

  // Function in charge of opening the image gallery
  const openGallery = async () => {
    const result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.All,
      allowsEditing: true,
      aspect: [4, 3],
      quality: 1,
    })

    if (!result.cancelled) {
      // console.log('buscando imagenes')
      setIsLoading(true) // uploading the image
      uploadImage(result.uri)
    }
  }

  // function to upload the images to Firebase
  const uploadImage = async (uri) => {
    const response = await fetch(uri)
    const blob = await response.blob()

    const storage = getStorage()
    const storageRef = ref(storage, `restaurants/${uuid()}`)

    // we go to storage where we want to save the images
    uploadBytes(storageRef, blob).then((snapshot) => {
      // console.log(snapshot)
      updatePhotosRestaurant(snapshot.metadata.fullPath)
    })
  }

  // we take the URL in the previous function and set it in the state of the form
  const updatePhotosRestaurant = async (imagePath) => {
    const storage = getStorage()
    const imageRef = ref(storage, imagePath)


    const imageUrl = await getDownloadURL(imageRef) // get the url

    // code to upload all images without replacing them
    // get the current images and add the new ones with the array
    formik.setFieldValue("images", [...formik.values.images, imageUrl])

    setIsLoading(false)
  }

  const removeImage = (img) => { // delete an image selected by the user
    Alert.alert(
      "Eliminar imagen",
      "¿Estás seguro de eliminar esta imagen?",
      [
        {
          text: "Cancelar",
          style: "cancel",
        },
        {
          text: "Eliminar",
          onPress: () => {
            const result = filter(
              formik.values.images,
              (image) => image !== img
            )
            formik.setFieldValue("images", result)
          },
        },
      ],
      { cancelable: false }
    ) 
  }

  return (

    <>
      <ScrollView
        style={Styles.viewImage}
        horizontal
        showsHorizontalScrollIndicator={false}
      >
        <Icon
          type="material-community"
          name="camera"
          color="#a7a7a7"
          containerStyle={Styles.containerIcon}
          onPress={openGallery}
        />
        {map(formik.values.images, (image) => ( // display the images on the screen
          <Avatar
            key={image}
            source=
            containerStyle={Styles.imageStyle}
            onPress={() => removeImage(image)}
          />
        ))}
      </ScrollView>
      <Text style={Styles.error}>{formik.errors.images}</Text>
      <LoadingModal show={isLoading} text="Subiendo la imagen" />
    </>
  )
}


from How to remove images from Firebase Storage?

No comments:

Post a Comment