user10279127
user10279127

Reputation:

firebase add user to realtime database upon sign up (javascript)

I'd need to create a users main node, that will have as child users id created upon sign up, as well as child elements dynamically populated later on (empty for now).

so my db would look like:

- users
     - uid
        - lists
            - list name
                - content
     - uid
     - uid
     ...

I'm still at the beginning and for now i'm trying to put the user id inside - users but doesn't work, the code (EDITED):

var refUsers = database.ref('users');

// Add sign up event
btnSignup.addEventListener('click', e => {
  // to do: check for real email
  const email = txtEmail.value;
  const pass = txtPassword.value;
  const auth = firebase.auth();
  // Sign in
  auth.createUserWithEmailAndPassword(email, pass)
  .then(function success(userData){
    var uid = userData.uid;
    refUsers.push(uid);
  })
  .catch(function(error) {
  // Handle Errors here.
  var errorCode = error.code;
  var errorMessage = error.message;
  alert('Error: ' + errorMessage);
  });
});

I also didn't understand if i should manually or programmatically create the main - users node inside the database, how (since it asks me for a value too) so for now i didn't create it at all, the documentation lack of many stuff imo.

Upvotes: 2

Views: 1236

Answers (1)

Arman Charan
Arman Charan

Reputation: 5797

The functionality you're describing can be achieved using Firebase Authentication Triggers.

ie.

const database = firebase.database()
const createUser = user => database.ref().child(`User/${user.uid}`).set(user)
exports.createUser = functions.auth.user().onCreate(createUser)

Upvotes: 3

Related Questions