2

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"); 
    });

Ticherhaz FreePalestine
  • 2,738
  • 4
  • 20
  • 46
jumper
  • 105
  • 10

1 Answers1

3

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

Peter Haddad
  • 78,874
  • 25
  • 140
  • 134
  • Error: Reference.child failed: First argument was an invalid path = "null". Paths must be non-empty strings and can't contain ".", "#", "$", "[", or "]".. why? i got this – jumper Oct 04 '19 at 05:14
  • try `firebase.database().ref("mycart").child(uid).once("value").then(function(snapshot) { if(snapshot.exists()){ console.log("snapshot"+snapshot.key); } console.log("snapshot doest exists"); });` – Peter Haddad Oct 04 '19 at 05:28
  • how are u retrieving the uid? – Peter Haddad Oct 04 '19 at 05:31
  • firebase.auth().onAuthStateChanged(function(user) { if (user) { uid = user.uid; }else{ } }); – jumper Oct 04 '19 at 05:32
  • 1
    okay do this `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{ } });` – Peter Haddad Oct 04 '19 at 05:37
  • its display snapshot-LqFt_A6mvO2rJI7ScJo, i have try. its work when im try call snaphot.val().quantity – jumper Oct 04 '19 at 05:49
  • if i call snaphot.val() display [object Object].. i also have try to call quantity, its work.. its just i wonder what actual problem at my previous code – jumper Oct 04 '19 at 05:56
  • yes snapshot.val().quantity should give you the quantity now, its because the `uid` was null `onAuthStateChanged` is asynchronous so when you were retrieving data outside of this method, the `uid` was null since it was not yet retrieved. https://stackoverflow.com/a/38354441/7015400 – Peter Haddad Oct 04 '19 at 05:58