Search code examples
javascriptreactjscloudinary

no response from destroy method of cloudinary


I am trying to delete the images from the client-side but destroy method not working, does not delete the images and at the same not giving me any error.

I am working with React.js and this is my method:

    deleteProductHandler = id => {

db.collection("products")
  .doc(id)
  .delete()
  .then(() => {

    // update the UI
    const products = [...this.state.products];
    let images = [];
    products.forEach((product, index) => {
      if (product.id === id) {
        products.splice(index, 1);
        images = [...product.images];
        this.setState({ show: false, products: products });
      }
    });

    // delete images from  cloudinary
    let links = images
      .map(link => {
        return link.match("products/");
      })
      .map(link => {
        const newlink = link.input.slice(link.index);
        const newlink2 = newlink.slice(0, -4);
        return { publicId: newlink2 };
      });

    let publicIds = [];
    for (let key in links) {
      publicIds.push(links[key].publicId);
    }

    console.log(publicIds);  
    // i got all publicIds here without any problem.
    // so dont wory about the code above.
    
    publicIds.forEach(publicId => {
      console.log(publicId);
      window.cloudinary.v2.uploader().destroy(publicId, (err, res) => {
      console.log(err, res);
      });
    });
  })
  .catch(err => {
    this.setState({ error: err });
  });
  };

this is the documentation of destroy method: https://cloudinary.com/documentation/image_upload_api_reference#destroy_method

what I am trying to get in here is that when the user deletes a product, automatically its images will be deleted from cloudinary.


Solution

  • It's not possible to delete images from the client-side directly because there's no way to authenticate such a request using details stored in the client - if you had your account's API secret available to the client, any of your users could use that secret to make arbitrary API calls to your account.

    In my app, I don't have any server-side component because I was working with firebase firestore, and what I am trying to do in the code above is to render destroy method in the client-side code, which is not possible.

    instead, you need a server-side component probably in node.js. that's a logical place to add a controller to handle deletion or other similar actions.