Function getting called multiple times javascript (react native)

时间:2017-12-17 08:13:50

标签: javascript firebase react-native firebase-realtime-database

Problem

I am adding likes to an app I am making. what should happen is the first time the user presses the like button, the likes on my server go up by one, along with a counter attached to that user's ID saying they liked the post, then we the user presses the button again to unlike the post, the likes will go down by one, and the counter saying that they liked the post will change showing that they didn't like the post.

What is actually happening when a user presses the button to like and dislike the post is the first time the likes go up by one, then when they press it again the likes go down by -2, then +3, then -4, +5 and so on. My guess is that the function is repeating itself multiple times or some other similar problem like that.

My code

 pressLike(key,likes,dislikes){
       var usersLiked = [];
    var query = firebase.database().ref('posts/'+key+'/usersVoted').orderByKey();
    query.once ('value', (snap) => {
      snap.forEach ( (child) => {       
       usersLiked.push({
         expoID:child.val().expoID
     });
     })
     }).then(() => {
      var addUserID = true;
             for (i = 0; i < usersLiked.length; i++) {
                if (usersLiked[i].expoID == expoID){
             var addUserID = false;
    }
    }
if (addUserID == true){
    firebase.database().ref('posts/'+key+'/votes/'+expoID).update({ voteNum: '0' })
    firebase.database().ref('posts/'+key+'/usersVoted').push().set({ expoID:expoID })
}
}).then(() =>{
firebase.database().ref('posts/'+key+'/votes/'+expoID).once("value", dataSnapshot => {
 voteNum=dataSnapshot.val().voteNum
 if (voteNum && voteNum == 1){
   firebase.database().ref('posts/'+key).update({ dislikes: dislikes - 1 });
   firebase.database().ref('posts/'+key).update({ likes: likes + 1 });
   firebase.database().ref('posts/'+key+'/votes/'+expoID).update({ voteNum: '2' });
  } else {
if (voteNum && voteNum == 2){
   firebase.database().ref('posts/'+key).update({ likes: likes - 1 });
   firebase.database().ref('posts/'+key+'/votes/'+expoID).update({ voteNum: '0' });
  } else {
if (voteNum && voteNum == 0){
   firebase.database().ref('posts/'+key).update({ likes:likes + 1 });
   firebase.database().ref('posts/'+key+'/votes/'+expoID).update({ voteNum: '2' });
  }}}
  })

})
}

Then later on I call the function with

 <TouchableWithoutFeedback onPress={() => {
this.getItems(); this.pressLike(item.key,item.likes,item.dislikes);
this.getItems();
   }}>

My Server

enter image description here This is an example of my server. The highlighted text is an example of an expoID, each expoID is different.

0 个答案:

没有答案