Aarush Sharma
Aarush Sharma

Reputation: 139

Deleting the document from Firebase with unique id

The below is the useEffect and the function which adds a comment (document) to the firebase

const postComment = (event) => {        
            event.preventDefault()
            db.collection("posts").doc(postId).collection("comments").add({
            caption: comment,
            header: signInUser.displayName,
            timestamp: firebase.firestore.FieldValue.serverTimestamp()
        });
        setComment('');
    }
    useEffect(() => {
        let unsubscribe;
        if(postId){
            unsubscribe = db
            .collection("posts")
            .doc(postId)
            .collection('comments')
            .orderBy('timestamp', 'asc')
            .onSnapshot((snapshot)=>{
                setComments(snapshot.docs.map((doc) =>{
                    return{
                    commentIdTest : doc.id,
                    commentTest: doc.data()
                    }}
                ));
            });
        }
        return () => {
            unsubscribe();
        }
    }, [postId]);

Below is the react return function where I am mapping through the list of Comments

{comments.map((comment)=>(
                
                <div className="Post__commentIcon">
                    <p>
                        <b>{comment.commentTest.header}</b> {comment.commentTest.caption} 
                    </p>
                    <div className="post__DeletePost"><Button onClick={deletingComment}><strong>X</strong></Button></div>
                </div>
            ))} 

I want to delete the comment from firebase on click of the button which I have made above and the function for deleting the comment is below**

const deletingComment =(e, commentIdTest) =>{
        e.stopPropagation();
        db.collection("posts").doc(postId).collection('comments').orderBy('timestamp').get()
         .then((querySnapshot)=>{
            querySnapshot.forEach(function (doc){
                 doc.ref.delete();
            })
         });
    }

with the above function it is deleting the whole collection when I only want to delete the comment which is clicked.

Upvotes: 0

Views: 241

Answers (1)

Tarik Huber
Tarik Huber

Reputation: 7388

You need to specify the id of the comment you want to delete and change the code to something like this:

const deletingComment = (e, commentId) => {
  e.stopPropagation();
  db.collection("posts")
    .doc(postId)
    .collection("comments")
    .doc(commentId)
    .delete();
};

Upvotes: 1

Related Questions