Reputation: 236
I have the following js code where I try to login on the blog_root object and then use my user_root to listen for any changes with user_root.on("child_added",...)
var root = new Firebase( /*my firebase url*/);
var blog_root = root.child("blog");
var user_root;
console.log("====");
blog_root.authAnonymously(function(err, authData) {
if(err){
console.log("user not authenticated?"+err);
}else{
console.log("user authenticated?"+authData.uid);
if(authData){
user_root = blog_root.child(authData.uid);
user_root.set(authData);
}
}
},{
remember: "sessionOnly"
});
user_root.on(
"child_added", //event_name
function(snapshot) {
//called for each existing element and each new element
}
Using this code specifically my user_root object is shown to be undefined. I check my data and the anonymous user has been successfully added to the blog_root, but I cannot seem to be able to listen to changes on user_root.
What I gather is that the user_root.on("child_added") event is fired on my authentication statement, but this makes no sense to me because user_root is initialized inside the authentication statement.
Any clues?
Upvotes: 0
Views: 269
Reputation: 13266
The authAnonymously
method is asynchronous, and the callback is invoked after you first get to user_root.on('child_added', ...)
. Try moving this listener into the callback from authAnonymously
.
Also, note that each time you call authAnonymously()
, you're creating a new session. Sessions are automatically persisted by default. To check whether or not the user is already authenticated, try ref.getAuth()
, and only invoke authAnonymously()
if the user is unauthenticated (ref.getAuth() === null
).
Upvotes: 3