I am trying to retrieve the UID of a user I just created in Firebase using JavaScript. Below is my current code:
firebase.auth().createUserWithEmailAndPassword(email, pass).catch(function(error, data) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
newusercreateduuid = data.user.uid;
// ...
console.log(errorCode + ' Error Message: ' + errorMessage);
});
I have tried a variety of callbacks including userData, data, user, and many more, but they all return null. I cannot seem to find anything online. I did find another Stack Overflow post using userData, but that returned null for me. How can I retrieve the UID of the user I just created?
you need to add this:
You can access to the then method:
firebase.auth()
.createUserWithEmailAndPassword(email, password)
.then(function(user)
// user information is available here...
})
.catch(function(error, data) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
newusercreateduuid = data.user.uid;
// ...
console.log(errorCode + ' Error Message: ' + errorMessage);
});
Also, if you need to control the user log changes, you can do this:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
var displayName = user.displayName;
var email = user.email;
var emailVerified = user.emailVerified;
var photoURL = user.photoURL;
var isAnonymous = user.isAnonymous;
var uid = user.uid;
var providerData = user.providerData;
// ...
} else {
// User is signed out.
// ...
}
});
This will give you the user state after login. Source
Related
This question already has answers here:
Undefined is not a function this.setState
(5 answers)
React this.setState is not a function
(16 answers)
Closed 2 years ago.
So the Connection popup succeeded and prints all data i need from console but I suppose to put some data on a state as shown below but it saves as undefined and found this error on console
TypeError: Cannot read property 'setState' of undefined
Here is my code:
Twitter() {
var provider = new firebase.auth.TwitterAuthProvider();
firebase.auth().signInWithPopup(provider).then(function (result) {
// This gives you a the Twitter OAuth 1.0 Access Token and Secret.
// You can use these server sides with your app's credentials to access the Twitter API.
var token = result.credential.accessToken;
var secret = result.credential.secret;
// The signed-in user info.
var user = result.user;
// ...
console.log(result)
document.cookie = "twittertoken=" + token + ";";
document.cookie = "twittersecret=" + secret + ";";
username = result.additionalUserInfo.profile.screen_name
profilepic = user.photoURL
console.log(username + " " + profilepic)
this.setState(states => ({
twitter: {
...states.twitter,
authorized: true,
username: username,
profilepic: profilepic,
}
}))
})
.catch(function (error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
// ...
console.error(error)
})
}
}
Some says I have to put bind(this) after this.setState() but still give me an error TypeError: Cannot read property 'setState' of undefined
Any fix?
Okay so I've looked on YouTube, read tutorials and blog posts, what in lords name am I missing?
I am populating the following via firebase auth
auth.onAuthStateChanged(user => {
if (user) {
// User is signed in.
var displayName = user.displayName;
var email = user.email;
var emailVerified = user.emailVerified;
var photoURL = user.photoURL;
var isAnonymous = user.isAnonymous;
var uid = user.uid;
var providerData = user.providerData;
console.log(uid); // <---- This works
// ...
} else {
// User is signed out.
// ...
}
});
console.log(uid); // <---- This doesn't
Now upon using console.log() and passing the variables to it, the correct outputs are received however I can't use the variables outwith that function.
I've looked and looked and the word "var" keeps re-appearing commonly attached to the word "global"
I tried declaring the variables outwith the function i.e.
uid = user.uid;
and
var uid;
declared above the function and the exact same result.
Can someone point out what very obvious thing I'm missing, I'm not asking for code to be re-written or anything of the sort! Just an explanation of the key concept I'm failing to grasp here.
Many thanks in advance!
You could try:
let uid = "";
let displayName = "";
let email = "";
const user = await auth.onAuthStateChanged(user => user ? user : null);
if (user) {
uid = user.uid;
displayName = user.displayName;
email = user.email;
}
console.log(uid);
function sontinue() {
var user = firebase.auth().currentUser;
var uid = user.uid;
var adaRef = firebase.database().ref("User/" + uid);
if (adaRef.orderByChild("Role").equalTo("admin")) {
location.href = "DB.html";
} else {
location.href = "index.html";
}
}
I would like to link my "admin" account to DB.html and "user" account to index.html but i think i always failed in Retrieving the Child Value.
You're not retrieving the data from the server. Remember you need to call .once('value') to get your query and then iterate through the remaining code based onw hether their value is of admin or user. Firebase Docs has more explination I've amended your code and put it below
function sontinue() {
var user = firebase.auth().currentUser;
var uid = user.uid;
var adaRef = firebase.database().ref("User/" + uid).orderByChild("Role");
//you now need to retrieve the data
return adaRef.once('value').then((snapshot)=>{
return snapshot.forEach(snapshot=>{
if (snapshot.child("Role").val()==="admin") {
location.href = "DB.html";
} else {
location.href = "index.html";
}
return console.log("added");
})
})
}
If you just wanted to find out who was of the user type admin...i'd use this below...much more efficient.
function sontinue() {
var user = firebase.auth().currentUser;
var uid = user.uid;
var adaRef = firebase.database().ref("User/" + uid).orderByChild("Role").equalTo("admin");
//you now need to retrieve the data
return adaRef.once('value').then((snapshot)=>{
//you now have all the users that are just admins
return snapshot.forEach(snapshot=>{
location.href = "DB.html";
return console.log("added");
})
})
}
i want make system, after success create an account and set value on Firebase database, it will go to the other page. i has set go to next page but, not set value into database. the think is, i want to make sure after create and set value to database and the system will move to another page.
var email = document.getElementById("email_field");
var password = document.getElementById("password_field");
firebase.auth().createUserWithEmailAndPassword(email.value, password.value).then(function(user)
{
var user = firebase.auth().currentUser;
if (firebase.auth().currentUser !== null)
console.log("user id: " + firebase.auth().currentUser.uid);
LogUser(user.uid);
console.log("user id: " + user.uid);
}).catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
window.alert("Error : " + errorCode+"message"+errorMessage);
if(err = null){
}
// ...
});
function LogUser(user){
firebase.database().ref('tbluser').child(user).set({
email: email,
test:"ha"
});
location.replace("signin.html")
}
}
Check out the article here on how to use Firebase Database callbacks.
Your code should look something like this:
firebase.database().ref('tbluser').child(user).set({
email: email,
test: "ha"
}, function(error) {
if (error) {
// it failed, do something here
} else {
// Data saved successfully!
location.replace("signin.html")
}
})
Good luck!
i´m want to check if the user who want to sign in using the facebook or google auth in to my web app is register on the real time database of firebase, so the idea is after the user press the button of sign in with facebook/google, first check in to the real time database if the uid is already on the real time database before redirect the user to another URL, for this i´m using the next function:
app.auth = function(){
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
var users_ref = firebase.database().ref('dream_wedding_users');
var register_user;
var register = false;
users_ref.on('value', function(snapshot) {
register_user = snapshot.val();
});
$.each(register_user, function(index, val){
if(user.uid === index){
register = true;
}
})
if(!register){
firebase.auth().signOut();
$('#login').modal('hide');
$('#modal_register').modal('show');
return false;
}else{
$(window).attr('location', 'http://localhost/wedding/en/gallery_en.php');
}
}
});
}
and for the auth function just the regular auth function for facebook and google that attach to a button.
app.facebook_login = function(){
var provider = new firebase.auth.FacebookAuthProvider();
firebase.auth().signInWithPopup(provider).then(function(result) {
// This gives you a Facebook Access Token. You can use it to access the Facebook API.
var token = result.credential.accessToken;
// The signed-in user info.
var user = result.user;
// ...
}).catch(function(error) {
console.log(error)
});
}
app.google_login = function(){
var provider = new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithPopup(provider).then(function(result) {
// This gives you a Google Access Token. You can use it to access the Google API.
var token = result.credential.accessToken;
// The signed-in user info.
var user = result.user;
// ...
firebase.auth().signInWithRedirect(provider);
}).catch(function(error) {
console.log(error);
});
}
my problem is the next one, when i click sign in facebook or google, first login the user, then redirect the user, then check is the user is register on the real time data base and then logout the user if is not register and then show the modal. i don´t want that redirect the user i want that check if the user is register and then show the modal of "register" if the user is not register without redirect, and redirect if the user is register.
You want to add a unique user , if it is already not registered right ?
here is the valid way:
var usernew = result.additionalUserInfo.isNewUser
console.log('Is this a new user ? => ' + usernew );
complete code is as follows:
var provider = new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithPopup(provider).then(function(result){
var usernew = result.additionalUserInfo.isNewUser;
console.log('Is this a new user ? => ' + usernew );
if (usernew == true) {
NewUser();
}
var token = result.credential.accessToken;
user = result.user;
// alert(JSON.stringify(user.photoURL))
}).catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
var email = error.email;
var credential = error.credential;
});
add user if it is not registered:
function NewUser(){
firebase.database().ref('/users').push({
Name : 'Johnson'
Age : '22'
})
}