Firebase javascript auth user displaying null even though user is signed in - javascript

I followed the Firebase docs for web development and I used the user.updateProfile method to add a display name to the user's profile. After signing in, I used console.log(user) and it worked but when I call updateProfile(), the value of user is null. Any solutions?
Here is the relevant code:
var button = document.getElementById("profile-button");
var username = document.getElementById("username-Box").value;
var user = firebase.auth().currentUser;
auth.onAuthStateChanged(user =>{
console.log(user);
})
function updateProfile(){
if (user != null){
user.updateProfile({
displayName : username
}).then(user => {
console.log("Updated Successfully");
window.location.href="chatpage.html";
}).catch(err =>{
console.log(err);
window.alert(err);
});
}else if(user == null){
console.log("No user signed in");
}
}

You need to wait for onAuthStateChanged to fire before assigning the user variable, otherwise the Auth object may be in an intermediate state. This is documented:
By using an observer, you ensure that the Auth object isn't in an intermediate state—such as initialization—when you get the current user. When you use signInWithRedirect, the onAuthStateChanged observer waits until getRedirectResult resolves before triggering.
You can also get the currently signed-in user by using the currentUser property. If a user isn't signed in, currentUser is null:
It's worth explicitly pointing out that the user variable you console.log in onAuthStateChanged is not the same user variable that's used in your updateProfile method. While the user maybe "logged in" when onAuthStateChanged fires, they are likely not logged in when you set your outer user variable. Therein lies your problem.
It's not clear from your code where updateProfile is called, but Peter Haddad's answer is likely the solution I would implement. However, note that with the code snippet supplied in that answer you'll also need to change your updateProfile method to accept a user parameter. Another approach would be to assign the user variable inside of onAuthStateChanged.
let user;
auth.onAuthStateChanged(u => user = u);
With that approach your updateProfile method should work as is. Just keep in mind that you may have a race condition depending on when you call updateProfile.

Since console.log(user) is returning the correct user, then inside the authstatechanged call the updateProfile:
auth.onAuthStateChanged(user =>{
console.log(user);
updateProfile(user);
})

Based on your snippet, I am assuming that updateProfile() is your onClick/onSubmit event handler for clicking your "update profile" button.
Because of this, your user is likely to have logged in by the time they press the button and therefore it is safe to use firebase.auth().currentUser in your event handler rather than maintain a user object in the global scope.
var eleButton = document.getElementById("profile-button");
var eleUsername = document.getElementById("username-Box");
function updateProfile() {
let user = firebase.auth().currentUser;
if (!user) {
alert('Please log in before clicking update profile!')
return;
}
// get current value of '#username-Box'
let username = eleUsername.value.trim();
if (!username) {
alert('Please enter a valid username!')
return;
}
user.updateProfile({
displayName : username
}).then(user => {
console.log("Updated Successfully");
window.location.href="chatpage.html";
}).catch(err =>{
console.log(err);
window.alert(err);
});
}
In your original code, you had the following:
var user = firebase.auth().currentUser; // <-- global-scope variable
auth.onAuthStateChanged(user =>{ // <-- function-scope variable
console.log(user);
})
When onAuthStateChanged fires, it does log the value of user, but it sets and logs it's own version of user, not the user variable in the global-scope.
If you wanted to update the global-scope version, you need to rename the variable used in your onAuthStateChanged handler so that it doesn't shadow the user global-scope variable.
var user = firebase.auth().currentUser; // <-- global-scope variable
auth.onAuthStateChanged(_user =>{ // <-- function-scope variable
user = _user;
console.log(user);
})

Related

Firebase anonymous auth is triggering both sides of a JS if statement

I have followed the Google reference documents but find that the firebase auth triggers both sides of the if statement.
calcbtn.addEventListener('click', e => {
//Auth
firebase.auth().signInAnonymously().catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
console.log(`${errorCode}: ${errorMessage}`);
// ...
});
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
var isAnonymous = user.isAnonymous;
uid = user.uid;
console.log(`UserID: ${uid}`);
// ...
} else {
// User is signed out.
console.log('Error: User is not authenticated');
// ...
}
// ...
});
Returns both the userID and the Error: User is not authenticated?
Initially when you attach the onAuthStateChanged, no user will be signed in yet. So at that point your callback will be called with null.
Then the user sign in triggered by signInAnonymously() completes and another call is made to your callback with that user object.
This is normal operation for an auth state listener in Firebase: it will usually initially be called with null, and then with the actual user object.

Wait for firebase.auth initialization before reading another function

I am very new with firebase and javascript.
My project: Build a private messaging app. To do that, I want to define a sub collection in firestore for private messaging using the current user id and the destination user id.
Here is the function that allows this:
// generate the right SubCollection depending on current User and the User he tries to reach
function dmCollection(toUid) {
if (toUid === null) {
// If no destination user is definer, we set it to the below value
toUid = 'fixed_value';
};
const idPair = [firebase.auth().currentUser.uid, toUid].join('_').sort();
return firebase.firestore().collection('dms').doc(idPair).collection('messages');
};
My problem: I want to use the firebase.auth().currentUser.uid attribute, but it looks like the function is not waiting for firebase.auth initialization. How can I fix this problem?
Additional information:
I have two functions that are calling the first one (dmCollection):
// retrieve DMs
function messagesWith(uid) {
return dmCollection(uid).orderBy('sent', 'desc').get();
};
// send a DM
function sendDM(toUid, messageText) {
return dmCollection(toUid).add({
from: firebase.auth().currentUser.uid,
text: messageText,
sent: firebase.firestore.FieldValue.serverTimestamp(),
});
};
If I correctly understand your problem ("it looks like the function is not waiting for firebase.auth initialization"), you have two possible solutions:
Solution 1: Set an observer on the Auth object
As explained in the documentation, you can set an observer on the Auth object with the onAuthStateChanged() method:
By using an observer, you ensure that the Auth object isn't in an
intermediate state—such as initialization—when you get the current
user.
So you would modify your code as follows:
// retrieve DMs
function messagesWith(uid) {
return dmCollection(uid).orderBy('sent', 'desc').get();
};
// send a DM
function sendDM(toUid, messageText) {
return dmCollection(toUid).add({
from: firebase.auth().currentUser.uid,
text: messageText,
sent: firebase.firestore.FieldValue.serverTimestamp(),
});
};
// generate the right SubCollection depending on current User and the User he tries to reach
function dmCollection(toUid) {
if (toUid === null) {
// If no destination user is definer, we set it to the below value
toUid = 'fixed_value';
};
const idPair = [firebase.auth().currentUser.uid, toUid].join('_').sort();
return firebase.firestore().collection('dms').doc(idPair).collection('messages');
};
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
var messageText = '....';
sendDM(user.uid, messageText)
} else {
// No user is signed in.
}
});
Solution 2: Use the currentUser property
You could also "get the currently signed-in user by using the currentUser property" as explained in the same doc. "If a user isn't signed in, currentUser is null".
In this case you would do:
var user = firebase.auth().currentUser;
if (user) {
var messageText = '....';
sendDM(user.uid, messageText);
} else {
// No user is signed in.
// Ask the user to sign in, e.g. redirect to a sign in page
}
Which solution to choose?
It depends how you want to call the function(s) based on the user uid.
If you want to call the function(s) immediately after the user is signed in, use Solution 1.
If you want to call the function(s) at another specific moment (e.g. following a user action), use Solution 2.

Input Value doesn't save, when pushing onto array gives undefined value

I am trying to update the user account details in firebase but I have noticed that the input value for one of my fields keeps coming up as undefined even when I console.log it. I am working in two files one is a loginjs file in which I am defining the user input.
signUpForm.addEventListener('click', function (e) {
e.preventDefault();
isSigningUp = true;
var email = signUpEmailInput.value;
var password = signUpPasswordInput.value;
var displayNameUser = displayNameInput.value;
var userPrivateKey = signUpPrivateKey.value;
var user = firebase.auth().currentUser;
var photoURL = "https://www.gravatar.com/avatar/" + md5(email);
if (signUpPasswordInput.value !== signUpPasswordConfirmInput.value) {
setSignUpError('Passwords do not match!');
} else if (!displayNameUser) {
setSignUpError("Display Name is required!");
} else if (!userPrivateKey) {
setSignUpError('You need to set a Private Key!');
} else {
auth.createUserWithEmailAndPassword(email, password)
.then(function (user) {
user.updateProfile({
displayName: displayNameUser,
photoURL: photoURL,
privateKey: userPrivateKey
}).then(function () {
// Update successful.
window.location.href = 'chat.html';
}).catch(function (error) {
// An error happened.
window.alert("Some unexpected error happened!");
});
user.sendEmailVerification().then(function () {
// Email sent.
}).catch(function (error) {
// An error happened.
window.alert("Email was not able to send!");
});
})
.catch(function (error) {
// Display error messages
setSignUpError(error.message);
});
}});
The weird thing is that the user input for my displayname and photoURL are working just fine, but when it comes to my private key user input it registers the input when it goes to the chat page and I do a console.log(user.privatekey) It says it is undefined.
In my chatjs file, thats when I am pushing the all the user profile information. The chatjs file basically allows a user to send a message, the message and all the user profile information gets stored onto the firebase database.
messages.push({
displayName: displayName,
userId: userId,
pic: userPic,
text: myString.toString(),
privatekey: user.privatekey,
timestamp: new Date().getTime() // unix timestamp in milliseconds
})
.then(function () {
messageStuff.value = "";
})
.catch(function (error) {
windows.alert("Your message was not sent!");
messageStuff;
});
The thing again is that the privatekey does not get stored at all, which is what I am not understanding, since it is registering user input in the loginjs file but when I go to the chatjs file it keeps saying the value is undefiend. I have googled everywhere and I still haven't found a solution to it. Any help would be greatly appricated!
It's because the Firebase user object you receive from Firebase is not customizable. When you call the createUserWithEmailAndPassword(email, password) method, it returns a specifically defined user object back to you - check out the docs for the properties of this object.
The properties displayName and photoURL both work because they are already properties of the user returned. privateKey is not an existing property of the Firebase user object, and Firebase doesn't know how to handle an update call for a property that isn't defined. Check out this question & answer where Frank explains that Users in Firebase aren't customizable - you need to store any extra info separately.

unable to get name, and output is undefined

I'm trying to get the user name, but the output is undefined. I still new to javascript on firebase.
firebase.auth().onAuthStateChanged(function (user) {
if (user) {
document.getElementById('welcome').innerHTML = 'Welcome! '+ user.name;
window.user = user;
alert( user.email);
// User is signed in.
}
you may want to use the displayName property instead of name. Have a look at the documentation to see which properties the user object provides.

Firebase Web - currentUser returns null

I'm trying to get my current user after the login, but this returning null.
There's my code:
var currentUser;
firebase
.auth()
.onAuthStateChanged(function(user){
currentUser = user;
console.log(currentUser); //this returns my user object
});
console.log(currentUser); //this returns "undefined"
var otherCurrentUser = firebase.auth().currentUser;
console.log(otherCurrentUser); // this returns "null"
var otherCurrentUser = firebase.auth().currentUser;
This will return null because auth object has not been initialized, you need an observer to do that.
While Login, use observer and save the UID in localstorage, and while logout clear the localstorage
Observer
var currentUser;
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
currentUser = user.uid;
console.log(currentUser); //this returns my user object
window.localStorage.setItem("UID",currentUser);
} else {
currentUser = "Error"
console.log(currentUser); //this returns my user object
window.localStorage.setItem("UID",currentUser);
alert(" Error in your login code");
// No user is signed in.
}
});
After this, whenever you need to get the user id, just use
var getuid = window.localStorage.getItem("UID")
console.log(getuid) // will log the UID
While logout just remove it
window.localStorage.removeItem("UID");
Hope this helps..!
The onAuthStateChanged event fires whenever the user's authentication state changes. The user variable is only useful within that callback. You cannot transport it out of that function.
So all code that requires a user should be inside the callback:
var currentUser;
firebase
.auth()
.onAuthStateChanged(function(user){
currentUser = user;
console.log(currentUser); //this returns my user object
});
For more on this, see some of these:
Using variable outside of ajax callback function
How do I return the response from an asynchronous call?
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
Firebase Query inside function returns null

Categories