Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase Returning user object after account creation

Im trying to create a user within Firebase and then create a user profile within the database on a web server. I have implemented the following code which creates the user quite nicely. However im not sure on how to receive the user id (which i need for a unique ID) to create the database structure. Is there a way to return a user object when the createUserWithEmailAndPassword is called?

I have tried to implement a firebase.auth().onAuthStateChangedfunction but i then receive a timeout error

If you havn't gathered this is for a web app.

<script>
function createUser() {
var Result = "true";
var textUser = document.getElementById('userName').value;
var textPassword = document.getElementById('userPassword').value;
var textAccountID = document.getElementById('accountRef').value;
var textDateCreated = document.getElementById('dateCreated').value;
var textDisplayName = document.getElementById('displayName').value;
var UID;

firebase.auth().createUserWithEmailAndPassword(textUser, textPassword).catch(function(error) {
  // Handle Errors here.
  var errorCode = error.code;
  var errorMessage = error.message;
  return Result = "false";
  // ...
});

writeUserData(UID, textDisplayName, textAccountID, textDateCreated);

return Result;

}

function writeUserData(userId, displayName, accountID, dateCreated) {
  firebase.database().ref('User/' + userId).set({
  userId:{
    AccountID: accountID,
    Created: dateCreated,
    Name: displayName}
  });
}


</script>
like image 549
PowerMan2015 Avatar asked Jun 02 '16 21:06

PowerMan2015


2 Answers

In order to get the user id in the client side you should do this:

firebase.auth().createUserWithEmailAndPassword(textUser, textPassword)
.then(function(user){
  console.log('uid',user.uid)

  //Here if you want you can sign in the user
}).catch(function(error) {
    //Handle error
});

as it is described here:

https://firebase.google.com/docs/reference/js/firebase.auth.Auth#createUserWithEmailAndPassword

Returns non-null firebase.Promise containing non-null firebase.User

like image 80
Ymmanuel Avatar answered Oct 19 '22 04:10

Ymmanuel


Looks like firebase has made some changes on this method. The accepted solution needs a little fix:

firebase.auth().createUserWithEmailAndPassword(textUser, textPassword)
.then(function(data){
  console.log('uid',data.user.uid)

  //Here if you want you can sign in the user
}).catch(function(error) {
    //Handle error
});

Now you get to acces the user via data.user

Hope this helps :)

like image 26
Gerardo BLANCO Avatar answered Oct 19 '22 05:10

Gerardo BLANCO