John Doah
John Doah

Reputation: 1999

Use Firebase to create database of users

I'm using firebase to auth users. I want to add a user (after he signs up to the application) to be added to a database. the user is signing up to the app with this:

  firebaseRef.auth().createUserWithEmailAndPassword(this.state.email, this.state.password).then(function(newUser){
    //good
    this.setState({
      status: 'ok'
    });
  }).catch(function(error){
    //bad
  });

after this code, the user do show up in the 'Authentication' section in the Firebase console.

I also want to add it to a database.

in this database, I want to have a list of users. each user should have few properties, like name, email and a list of friends (other users).

I'm searching how to do so, but I still don't have a clue. Would appreciate if you guys could give me information source/examples.

Thanks in advance!

Upvotes: 1

Views: 566

Answers (1)

Jay
Jay

Reputation: 35648

Standard practice is to have a /users node within your Firebase.

Once the user is created they will be assigned a user id (uid) which can be obtained within the closure following the create function.

Within your user node you would create a node using their uid as the key and then any other data you want to store about them.

users
   uid_0
     nickname: "Michael"
   uid_1
     nickname: "Jermaine"

To write, do something like this

firebaseRef.auth().createUserWithEmailAndPassword(this.state.email, this.state.password).then(function(authData){
    this.writeUserData(authData.uid, users_nickname);
  }).catch(function(error){
    //bad
  });


writeUserData(the_uid, the_nickname) {
    // the_uid can also come from let userId = firebaseApp.auth().currentUser.uid;
    firebase.database().ref('users/' + the_uid + '/').set({
        nickname: the_nickname,
    });
  }

which will add the following to Firebase

users
   uid_x
     nickname: "some nickname"

(on my iPad so untested but you get the idea)

Upvotes: 1

Related Questions