Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

102
Views
Only run write value at realtime database only once
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!