I'm trying to run a delete function that should be fairly straight forward but i'm not getting it.
I referenced the document within the sub-collection but it doesn't seemed to be referenced correctly. When I hard code the answer documents id it performs the function but when I try to reference it doesn't work.
I have the document information stored in an array but I need to cycle through the array to find the id that matches the post. I'm having trouble grabbing the reference from 'getAnswer' once it is stored.
Here is the code:
const [getAnswer, setGetAnswer] = useState([]);
useEffect(() => {
let mounted = true;
db.collection("questions")
.doc(questionId)
.collection("answer")
.orderBy("timestamp", "desc")
.onSnapshot((snapshot) => {
if (mounted) {
setGetAnswer(
snapshot.docs.map((doc) => ({
id: doc.id,
answers: doc.data(),
}))
);
}
});
return () => (mounted = false);
}, []);
const handleDeletePost = (e) => {
if (user) {
db.collection("questions")
.doc(questionId)
.collection("answer")
.doc(getAnswer.id)
.delete();
}
};
const answerMenuId = "primary-answer-account-menu";
const answerRenderMenu = (
<Menu
anchorEl={anchorEl}
anchorOrigin={{ vertical: "top", horizontal: "right" }}
id={answerMenuId}
keepMounted
transformOrigin={{ vertical: "top", horizontal: "right" }}
open={isMenuOpen}
onClose={handleMenuClose}
>
<MenuItem onClick={handleMenuClose}>Edit</MenuItem>
<MenuItem onClick={handleMenuClose} onClick={handleDeletePost}>
Delete
</MenuItem>
</Menu>
);
For a bit more context I would like to delete an answer document based on the id of the document. Here is a screenshot of the database: