testerprox
testerprox

Reputation: 55

Firebase cloud functions - write to database on create user

I want to write to database, every time a new user is registered. This is my code:

    const functions = require('firebase-functions');
    exports.newUserToDatabaseTest = functions.auth.user().onCreate((user) => {
    var current = new Date().toString();
    firebase.database().ref('users/' + firebase.auth().currentUser.uid).set({
        email: user.email,
        creationDate: current
        })
  });

It deploys correctly, but nothing is happening after a new user registers in my React Native app. What am I doing wrong?

Upvotes: 1

Views: 791

Answers (1)

Tarik Huber
Tarik Huber

Reputation: 7388

When writing Firebase Cloud Functions always take care that you need to "tell" the function to wait if you run async code. Otherwise it will stop before your code executes. For that we return your set to the database.

Also the auth trigger gives you the user so you can use that to get the user uid.

The firebase.auth().currentUser.uid will not work in cloud functions.

Try changing your code to something like this:

  const functions = require('firebase-functions');

  const admin = require('firebase-admin');
  admin.initializeApp();

    exports.newUserToDatabaseTest = functions.auth.user().onCreate((user) => {
    var current = new Date().toString();
    return admin.database().ref('users/' + user.uid).set({
        email: user.email,
        creationDate: current
        })
  });

Upvotes: 1

Related Questions