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().onAuthStateChanged
function 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>
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
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With