Skip to content
Advertisement

Get points of user that is currently logged in from realtime database

I want to get the points and show to the owner of that account when he is logged in I tried reading firebase documentation but I couldn’t made it here is the code that I use for assigning the random key and saving the child data

const autoid = firebase.database().ref("user").push().key;
firebase.database().ref("user").child(autoid).set({
  Email :email,
  Password : password,
  Points :"500"
});

Picture of database

I want whenever the user is login get his points from database and show it on their profile.

Advertisement

Answer

In your code you are generating a random key and then assigning it to a variable. A better way to do is to get the userId and assign it as a documentid and then when retrieving the data use the userId to get the user’s data.

For example, to add the data:

const database = firebase.database();
const user = firebase.auth().currentUser;
if (user !== null) {
  // Add user data in collection "users"
 database.ref("users").child(user.uid).set({
    email :email,
    password : password,
    points :"500"
   })
  .then(() => {
    console.log("data successfully written!");
   })
  .catch((error) => {
    console.error("Error writing data: ", error);
  });
}

Then after the user logins in, you can do the following to retrieve points:

const database = firebase.database();
const user = firebase.auth().currentUser;
if (user !== null) {
  let ref = database.ref("users").child(user.uid);
  ref.get().then((snapshot) => {
    if (snapshot.exists()) {
        console.log("data:", snapshot.val());
        console.log(snapshot.val().points);
    }
  }).catch((error) => {
    console.log("Error getting data:", error);
  });
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement