Home > Software design >  How to add previous data with new one in firebase realtime database javascript
How to add previous data with new one in firebase realtime database javascript

Time:03-15

function add(){
  firebase.database().ref("user/l6xetRv3ddhjlerJm10d3aYkF3w1" ).update({            
    points: "2000"
  })
}

I am using this code above to update a specified user points for test but I want to update points of currently logged in user. I tried doing it on function onAuthStateChanged block, but it was unsuccessful. Any suggestions how should I do it?

And is it possible to update previous points adding with current update points? for example:- the previous points of user is 2000, the update function updates 2000 points but i want it to update previous points current points which is goona be update (2000 2000).

CodePudding user response:

To write the points of the currently sign in user:

const uid = firebase.auth().currentUser.uid;
firebase.database().ref("user").child(uid).update({            
  points: "2000"
})

To increment/decrement the points of the user, you can use the atomic increment operator:

const uid = firebase.auth().currentUser.uid;
firebase.database().ref("user").child(uid).update({            
  points: firebase.database.ServerValue.increment(2000);
})
  • Related