[英]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我正在尝试从 firebase firestore 集合中删除一个文档我该怎么做,我尝试了一些但没有成功这是我的代码
here is the Firestore hook这是 Firestore 挂钩
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)显示所有图像的图像网格(只有 js 没有 jsx 返回)
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.现在,在 imagegrid jsx 上,我拥有所有上传的图像,这些图像将文档存储在其中。
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所以我为每个图像添加了一个按钮,我希望当我单击该按钮时它会触发一个 handleDelete() 从 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()
.如果您尝试使用一个按钮来删除单个文档,您可能不想遍历所有文档并调用
deleteDoc()
。
Instead, your UI would likely display each image and include its ID for each button.相反,您的 UI 可能会显示每个图像并包含每个按钮的 ID。 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>;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.