简体   繁体   中英

Delete image Doc from firebase firestore

I am trying to delete a document from firebase firestore collection how can I do that, I tried few things but no success here is my code

here is the Firestore hook


const useFirestore = (somecollection) => {

    const [docs, setDocs] = useState([]);


    useEffect (() => {
        // new collection reference
          const newcoll = collection(projectFirestore, somecollection);
          const q = query(newcoll, orderBy('createdAt', 'desc'));
          const unsub = onSnapshot(q, (snapshot) => {
            let documents = [];
            snapshot.forEach(doc => {
               documents.push({...doc.data(), id: doc.id})
            })
            setDocs(documents);
          });
     
          return () => unsub;

    },[somecollection]);
    
    return { docs };
}

the imagegrid where all the images are shown (only the js without the jsx return)

const { docs } = useFirestore('images');

  const handleDelete = (e) => {
    docs.forEach(doc => {
      deleteDoc(doc);
    })

now, on the imagegrid jsx I have all the uploaded images that store the document in them.

so I added a button to every image and I want that when I click the button its fires a handleDelete() that delete this specific image document from the firestore

If you are trying to have a button that deletes a single document, you likely do NOT want to be looping over all of the docs and calling deleteDoc() .

Instead, your UI would likely display each image and include its ID for each button. Something like:

const deleteOneImageDoc = async (docId) => {
  try {
    let docRef = doc(myFirestore, `images/${docId}`);
    await deleteDoc(docRef);
  } catch (ex) {
    console.error(`Delete FAILED: ${ex.message}`);
    throw ex;
  }
};

return <div>
  docs.map((imgDoc) => {
    return (
      <div key={imgDoc.id}>
        <img src={imgDoc.url}/>
        <button onClick={() => deleteOneImageDoc(imgDoc.id)}>
          delete {imgDoc.id}
        </button>
      </div>);
    })
  </div>;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM