firebase.auth().onAuthStateChanged(function(user) {
if (user){
firebase.database().ref("users/" + user.uid).set({
email:user.email,
points:"500",
uid: user.uid
})
var query = firebase.database().ref("users").child(user.uid);
query.once("value").then(function(snapshot) {
var email = snapshot.val().Email;
var point = snapshot.val().points;
document.getElementById("points").innerHTML=point;
});
The code above is for writing and retrieving the data from database, but it is not going according to plans. Whenever there is changes on points, it automatically restores points to 500. Is there a way where a user's data is written only once?
It sounds like you only want to write the initial points if the user data doesn't exist yet. For that you can use a transaction:
if (user){
const userRef = firebase.database().ref("users/" + user.uid);
userRef.transaction((current) => {
if (!current) return {
email:user.email,
points:"500",
uid: user.uid
}
})
...
This returns the initial value if no data exists yet. Since it returns no value otherwise, the transaction is aborted when data already exists.