Home > other >  I want to make sure the Post Is Not Liked multiple times by The same user using Firebase
I want to make sure the Post Is Not Liked multiple times by The same user using Firebase

Time:11-09

I have these codes to make the Like functionality

/*Here I increment by 1 every time someone submit like*/ 
db.collection("post").doc(postId).update({
    likes: increment
})

/*Here I collect the uid of the user who submit Like and append to an Array*/
db.collection('post').doc(postId).update( {
      usersArray: firebase.firestore.FieldValue.arrayUnion( userId )
   });

now is possible to have code that runs every time someone submits Like to check if the user already exists in the usersArray?

CodePudding user response:

Before updating the post document, you first need to read it in order to check if userId is already included in the usersArray array.

For that you shall use a Transaction to ensure that the document was not modified between the time you read it for checking the Array and the time you update it.

const postDocRef = db.collection('post').doc(postId);

return db
.runTransaction((transaction) => {
    // This code may get re-run multiple times if there are conflicts.
    return transaction.get(postDocRef).then((postDoc) => {
        if (!postDoc.exists) {
            throw 'Document does not exist!';
        }

        if (postDoc.data().usersArray.includes(userId)) {
            throw 'User has already liked this post!';
        }

        const newLikes = postDoc.data().likes   1;
        transaction.update(postDocRef, {
            usersArray: firebase.firestore.FieldValue.arrayUnion(userId),
            likes: newLikes,
        });
    });
})
.then(() => {
    console.log('Transaction successfully committed!');
})
.catch((error) => {
    console.log('Transaction failed: ', error);
});

Keep in mind that even with this code, malicious users can still use your configuration data with their own code to write their UID into the array a second time. To prevent this, you'll want to write security rules to only allow adding the UID if it isn't in the array already (by comparing request.resource with resource).

CodePudding user response:

Use cloud functions for counter increments like post likes.We can get updated and previous value of document in onUpdate function trigger on post collection,then we can check if user is already included in userArray and increment/decrement like count accordingly.

  • Related