Ola
Ola

Reputation: 431

Authenticate user and add them DB simultaneously

I want to signup new users (through auth) and then add them (with their names and other info) to my user list database in realtime DB. I can't figure out what I'm doing wrong. Authentication works great but the new user is not being added to the DB.

    var fname = document.getElementById('fname').value;
    var lname = document.getElementById('lname').value;
    var email = document.getElementById('email').value;

in the code below, I register them then add their names to the DB and then send a verification email.

function handleRegister() {
     var ref = firebase.database().ref();
     console.log(email);
     console.log(fname);

        if (email.length < 4) {
        alert('Please enter an email address.');
        return;
      }
      if (password.length < 4) {
        alert('Please enter a password.');
        return;
      }

      firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {


      // Handle Errors here.
      var errorCode = error.code;
      var errorMessage = error.message;
      var uid = firebase.auth().currentUser.uid; 
      // [START_EXCLUDE]
      if (errorCode == 'auth/weak-password') {
        alert('The password is too weak.');

             firebase.auth().onAuthStateChanged(user => {
        if(user) {

              var postData = {
                Fullname: fname + lname,
                  email: email,
              };

              // Write the new post's data simultaneously in the posts list and the user's post list.
              var updates = {};
              updates['/Users/' + uid ] = postData;

              return firebase.database().ref().update(updates);

        }
      })
      } else {
         console.log(error);

    }

  })

Authentication and send email verification works fine but names are not being added to the DB. Also if there is a better approach to achieve auth,add to DB and send email verification, please let me know. Please help.

This is the updated addition

var addusertoDB = function(user){

           var uid = firebase.getAuth().uid;
           var postData = {
            Firstname: fname,
            Lastname: lname,
            email: email,
          }
            // Get a key for a new Post.
          var newPostKey = firebase.database().ref().child('Users').push().uid
          // Write the new post's data simultaneously in the posts list and the user's post list.
          var updates = {};
          updates['/Users/' + newPostKey] = postData;
          // updates['/user-posts/' + '/' + newPostKey] = postData;
          return firebase.database().ref().update(updates);
    }

and handle register has been updated to

  firebase.auth().createUserWithEmailAndPassword(email, password).then(


        addusertoDB).catch(handleCreateUserError);

it's finally being added to the DB (without the uid) but firebase.getAuth().uid is not getting the uid. the error I'm getting is "firebase.getAuth is not a function"

Upvotes: 0

Views: 59

Answers (1)

Susanne Peng
Susanne Peng

Reputation: 887

You are trying to handle both the errors and the user update in the same function you have passed to catch(). This means that any code inside that function is only run when firebase.auth().createUserWithEmailAndPassword(email, password) fails.

From the firebase documentation:

createUserWithEmailAndPassword

createUserWithEmailAndPassword(email, password) returns firebase.Promise containing non-null firebase.User

Creates a new user account associated with the specified email address and password.

On successful creation of the user account, this user will also be signed in to your application.

This means that on the successful creation of a user you will have access to the new user via a callback passed into then().

You probably want something like this:

var doSomethingWithNewUser = function(user) {
    // Manipulate the newly created User however you like here.
    // You don't have to sign them in again.
};

var handleCreateUserError = function(error) {
    var errorCode = error.code;
    var errorMessage = error.message;
    // Do whatever you want with the error codes.
};

firebase.auth().createUserWithEmailAndPassword(email, password)
    .then(doSomethingWithNewUser)
    .catch(handleCreateUserError);

Upvotes: 1

Related Questions