0
function rateProject(self) {

document.getElementsByClassName('modal')[5].style.display="block";
var docRef=self.getAttribute("id");
var downloadRef = db.collection("projects").doc(docRef);

    document.getElementById('rateOneStar').addEventListener('click',e=>{
        return downloadRef.update({
            oneStar: firebase.firestore.FieldValue.increment(1)
        })
        .then(function() {
            console.log("1 star given");
            document.getElementsByClassName('modal')[5].style.display="none";
        })
        .catch(function(error) {
            // The document probably doesn't exist.
            console.error("Error updating document: ", error);

        });

    })
}

This is what happens to oneStar:

(1 click: 1), (2 click: 3), (3 click: 6)

What I want:

(1 click: 1), (2 click: 2), (3 click: 3).

If I remove the eventListener it works.

  • 1
    I don't understand is this a question? What your problem? Your code works properly though. You are using FieldValue.increment(1) which increases the value of the field by 1. If the value was 3 and you run it will go to 4. – Chris Papantonis Mar 27 '20 at 13:25
  • Thanks for responding! If I click 3 times the field value will be 6, not 3 as I want. If I click four times the value will be 10 not 4 as I want. Each time I click the increment value becomes one more. I want the increment value to be constant. Hope you understand the problem better. –  Mar 27 '20 at 15:54
  • how many times do you call the function rateProject? – Chris Papantonis Mar 27 '20 at 16:22
  • It depends on how many times the user clicks a project(object). I got many different projects, and the function will launch when I user clicks on one of the projects. Of course I want the user to be able to click on every project visible, but the user don't have to. So it really depends on what the user does. Thanks again –  Mar 27 '20 at 16:35

1 Answers1

0

I believe that addEventListener is stacking up and each time you execute the function one more listener is added. If you want to confirm that this is happening by clicking 4 times the result should be 10. One possible solution is to clear the events listener each time from the element rateOneStar.

Chris Papantonis
  • 720
  • 7
  • 18
  • I can confirm that by clicking four times the result is 10. How to I clear the event listener? –  Mar 27 '20 at 19:16
  • I found the solution here: https://stackoverflow.com/questions/9251837/how-to-remove-all-listeners-in-an-element Thanks alot for the help! –  Mar 27 '20 at 19:29
  • Glad I could help. If my answer helped you mark it as accepted, so other people don't waste time trying to answer an already answered question. – Chris Papantonis Mar 27 '20 at 19:44