How can I UpdateUserProfile when signing up user, in Firebase-v9, with Typescript?

I’m trying to sign up user and then updateUserProfile with the so named function.

First I had a problem with the typeof user, which I solved by importing the User type from firebase and I do a check if there is a currentUser, to satisfy the null possibility.

I think the problem is with that last check, because the content of the function does not run. Namely I think the user is not yet signed up.

Note: if I do: const user: User = this.auth.currentUser;

I get in updateProfile(user) this error type 'User | null' is not assignable to type 'User'.

If I do: const user: User | null = this.auth.currentUser;

I get this error:

Argument of type 'User | null' is not assignable to parameter of type 'User'.

That’s why I ended up checking like this:

if (this.auth.currentUser) {
const user: User = this.auth.currentUser;

So how can I make this work?

An option could be to check onAuthStateChanged in home screen after signing up and then run updateUserProfile, where I would pass the name, which I would on sign up just save in redux.

In Firebase-v8 I could updateUserProfile just in createUserWithEmailAndPassword function.
I’m sure there should be a way to do it also in v9, but with Typescript too.

Any help would be appreciated.

Thanks

import { createUserWithEmailAndPassword, getAuth, sendPasswordResetEmail, updateProfile, User } from 'firebase/auth';


  async signUp(email: string, password: string, name: string) {
    createUserWithEmailAndPassword(this.auth, email, password)
      .then(async userCredential => {
        console.log('userCredential', userCredential);

        await this.updateUserProfile(name);
      }).catch((error) => {
        const errorCode = error.code;
        const errorMessage = error.message;
      })
  }

  async updateUserProfile(name: string) {

    if (this.auth.currentUser) {
      const user: User = this.auth.currentUser;

      updateProfile((user), {
        displayName: name, photoURL: `https://gravatar.com/avatar${md5(user.email)}?d=identicon`
      }).then((user) => {
        // Profile updated!
        console.log('Profile updated!', user);

      }).catch((error) => {
        // An error occurred
        console.log(error);

      });
    }
  }

>Solution :

The this.auth.currentUser can be null if the auth state has not loaded yet. In this case you can pass the user object from userCredential itself as shown below:

createUserWithEmailAndPassword(this.auth, email, password)
  .then(async userCredential => {
    console.log('userCredential', userCredential);
    await this.updateUserProfile(userCredential.user, name);
    // Pass user object from here ^^^
})

// Take user object as parameter
async updateUserProfile(user: User, name: string) {
  updateProfile((user), {
    displayName: name, photoURL: `https://gravatar.com/avatar${md5(user.email)}?d=identicon`
  })
}

Leave a Reply