DEV Community

badalpatel6534
badalpatel6534

Posted on • Updated on

Firebase Function current user update Phone Number

Firebase Function current user update Phone Number

AngularFireAuth update profile of the current user does not support phone number that why we need to firebase callable function for an update phone number after the update you log in from that number as well

1. Setup function for update phoneNumber

firebase init functions

Now, in index.ts file import function and admin

 
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
const serviceAccount = require('../serviceAccountKey.json');

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: "your-database-url"
});
 
Now, function for update user phoneNumber
 export const updateUserPhoneNumber = functions.https.onCall(
    async (request, context) => {
      try {
        const userUpdate = await admin.auth().updateUser(request.uid, {
          phoneNumber: request.phoneNumber
        });
        return userUpdate;
      } catch (e) {
        return e;
      }
    }
  );
 
The function is ready to deploy
 firebase deploy --only functions 

2. Call Function from Ionic v5

You Need to import firebase function module in app.module.ts
 import { AngularFireFunctionsModule } from '@angular/fire/functions';
 imports: [AngularFireFunctionsModule] 
In your page inject dependency in the constructor
 import { AngularFireFunctions } from '@angular/fire/functions';
 constructor(private functions: AngularFireFunctions) 
Now callable function call
const callable = this.functions.httpsCallable('updateUserPhoneNumber');
const obs = callable({ uid: user uid, phoneNumber:  user phone number});
          obs.subscribe(async res => {
            firebase.auth().currentUser.reload(); 
            firebase.auth().currentUser.getIdToken(true);}); 
// after update the user's phone number token refresh to contain the update phone number

That's it now arrange all things according to your requirement

Source code

https://github.com/badalpatel6534/firebase-function-update-user-phone-number

Top comments (0)