Reputation: 13
I am working on a small web app and I have hit a roadblock that I can't seem to overcome. I am able to register a new account, but I would like to save additional data to a database right after signing up.
This is what I have that I am confident that works fine.
$("#user-sign-up-button").click(function(){
var firstName = $("#new-user-first-name").val();
var secondName = $("#new-user-surname").val();
var charity = $("#new-user-charity-account").val();
var userEmail = $("#new-user-email").val();
var userPassword = $("#new-user-password").val();
var secondPassword = $("#new-user-repeated").val();
firebase.auth().createUserWithEmailAndPassword(userEmail, userPassword)
.catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
});
});
Now in regards to saving the additional variables to the database I have tried both of the below within .then part of createuserWithEmailAndPassword.
.then(
function(user){
var root = firebase.database().ref();
var uid = user.uid;
alert(uid);
var postData = { firstName: first_name,
secondName: second_name,
email: user_email,
isCharity: charity };
root.child("users").child(uid).set(postData);
}
function writeUserData(first_name, second_name, charity, user_email) {
firebase.database().ref('users/' + user.uid).set({
firstName: first_name,
secondName: second_name,
email: user_email,
isCharity: charity
});
)
Both of the above solutions work within onAuthStateChanged but I want to capture the data at sign up, not every time someone signs in.
Any assistance would be great.
Upvotes: 1
Views: 403
Reputation: 18595
You must use .onAuthStateChanged
to get at firebase.auth().currentUser
. It's asynchronous and will be empty/null
until it resolves. Also, don't forget that new email based accounts will not be .emailValidated:true
until they have clicked a verification email link. ...something to consider.
Upvotes: 1