jumper
jumper

Reputation: 105

Why my snapshot return null, even there have values on Firebase Database

I have a problem with the code regarding the snapshot where I'm trying to get the quantity value in my Firebase Database. I have captured my database.

console result

and

database

 firebase.database().ref("mycart/"+uid+"/"+imguid).once("value").then(function(snapshot) {
        console.log("uid="+uid); 
        console.log("imguid="+imguid); 
        console.log("snapshot.val()="+snapshot.val()); 
        if(snapshot.exists()){
           console.log("snapshot"+snapshot.key); 
        }
        console.log("snapshot doest exists"); 
    });

Upvotes: 2

Views: 1286

Answers (1)

Peter Haddad
Peter Haddad

Reputation: 80914

Try the following:

firebase.auth().onAuthStateChanged(function(user) { 
 if (user) { 
 uid = user.uid;
 firebase.database().ref("mycart").child(uid).child(imguid).once("value").then(function(snapshot) { 
   if(snapshot.exists()){ 
       console.log("snapshot"+snapshot.key);
      } 
      console.log("snapshot doest exists"); 
    }); 
   }
  else{ } });

The uid that was returning null thus you got that error. Retrieving authentication data in firebase is asynchronous therefore if you want to use the uid to retrieve data from the database, then you need to add it under onAuthStateChanged

Upvotes: 3

Related Questions