I'm makeing tests with Firebase Authentication from javascript client and I'm trying to retrieve the idToken with retrieve id tokens on clients documentation
I think I'm forgetting something basic.
A user is logged in with Google
The code is just i've seen in other posts and in the documentation. And the result is in the comments.
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
console.log(user); // this is shown. Firebase user and provider data
console.log(user.uid); // Shown
firebase.auth().user.getIdToken().then(function(idToken) {
console.log(idToken+'--'); // Nothing happens. No errors and the function not continues
});
console.log(user.uid); // Nothing happens
}
})
Thanks
EDIT:
if I add anything wrong nothing happens too. for example if I add an alert it shows the alert but if I have a mistake, for example alter() not shows any error. Added catch and nothing too
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
alter() // Nothing happens and the function stop
console.log(user); // this is shown. Firebase user and provider data
console.log(user.uid); // Shown
firebase.auth().user.getIdToken().then(function(idToken) {
console.log(idToken+'--'); // Nothing happens. No errors and the function not continues
}).catch(function(error) {
console.log(error+'--'); // Nothing
});
console.log(user.uid); // Nothing happens
}
})
firebase.auth().user
doesn't have the user
in that moment yet. You have to use the user
from firebase.auth().onAuthStateChanged
directly like this:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
console.log(user); // It shows the Firebase user
console.log(firebase.auth().user); // It is still undefined
user.getIdToken().then(function(idToken) { // <------ Check this line
console.log(idToken); // It shows the Firebase token now
});
}
});
You can only use firebase.auth().user
after firebase.auth().onAuthStateChanged
is completed and outside of its scope, otherwise it will be undefined.