2

I'm trying to create a new authenticated user whenever a new document is added in collection "users". The user details shall be provided in the new document in the fields "email" and "phone".

The code below only triggers when a new document is created but can not fetch the values in that document for creating an authenticated user with email, phone and a random userId.

import * as functions from 'firebase-functions';

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

admin.initializeApp();

exports.updateUser = functions.firestore

    .document('users/{user}').onCreate((snap, context) => {
      // ... Your code here

      const newValue = snap.data();

      const email = newValue.email;
      const phone = newValue.phone;

      console.log(newValue);

      console.log("new user added");

      admin.auth().createUser({
        uid: 'some-uid',
        email: email,
        phoneNumber: phone
      })
        .then(function() {
          // See the UserRecord reference doc for the contents of userRecord.
          console.log('Successfully created new user:');
        })
        .catch(function() {
          console.log('Error creating new user:');
        });


    });

I'm getting an error "Object possibly undefined" for the const "newValue" in these lines of code.

const email = newValue.email;
const phone = newValue.phone;
Doug Stevenson
  • 236,239
  • 27
  • 275
  • 302
Andrei Enache
  • 297
  • 1
  • 3
  • 13

1 Answers1

3

My first guess is that the typescript compiler can't know whether snap.data() has a value, so you'll need to check for that:

  const newValue = snap.data();

  if (newValue) {
    const email = newValue.email;
    const phone = newValue.phone;

    console.log(newValue);

If this is indeed the case, it might have the same problem later on, since it can't be sure that newValue has email and phone properties. If you get a similar message for those, you'll have to add a similar checks for them too.

Frank van Puffelen
  • 418,229
  • 62
  • 649
  • 645