After successfully creating an account, the displayName consistently appears as null

I have a Vue project that utilizes Firebase as the backend. User registration is done using email and password. Below is the method used in Firebase:

firebase.auth()
          .createUserWithEmailAndPassword(this.user.email, this.user.password)
          .then((res) => {
            res.user
              .updateProfile({
                displayName: this.user.username,
              })
              .then(() => {
              });
          })
          .catch((error) => {
            this.error = error.message;
            console.log("err", error);
          });

In my main.js file, I have an onAuthStateChanged method set up like this:

firebase.auth().onAuthStateChanged((user) => {
  if (user) {
    console.log("user", user);
    console.log("nme", user.displayName);
    console.log("email", user.email);
    store.dispatch("fetchUser", user);
  } else {
    store.dispatch("logout");
  }

This method gets triggered upon user registration. The issue I'm facing is that when a user is registered, the displayName property of the user appears to be null for some reason. It only gets a value after refreshing the page. Strangely, I can access the email immediately but not the displayName. Here is a screenshot from my console:

The first part shows the "console.log("user", user)" followed by other print statements. In the user object, you can see that displayName has a value, yet calling user.displayName returns null.

Could someone please explain why this behavior is occurring? Thank you in advance!

Answer №1

The reason for this behavior is that the updateProfile() function operates asynchronously and does not automatically trigger the onAuthStateChanged() listener.

Therefore, if the onAuthStateChanged() listener is invoked immediately after a user account is created (and signed in), the value of displayName may not have been updated yet.

To address this issue, it's advisable to update the state in your Vuex Store once the promise returned by the updateProfile() function has been fulfilled.

You can achieve this with a code snippet similar to the following:

  firebase
    .auth()
    .createUserWithEmailAndPassword(this.user.email, this.user.password)
    .then((res) => {
      return res.user.updateProfile({
        displayName: this.user.username,
      });
    })
    .then(() => {
      // Update the Vuex Store using firebase.auth().currentUser
      console.log(firebase.auth().currentUser.displayName);
    })
    .catch((error) => {
      this.error = error.message;
      console.log('Error occurred:', error);
    });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

serverless with Node.js and AWS encountering a 'TypeError' with the message 'callback is not a function'

Within my handler.js file, I am utilizing the getQuotation() function from the lalamove/index.js file by passing the string "hi" as an argument. 'use strict'; var lalamove = require('./lalamove/index.js'); module.exports.getEstimate = ...

Is there a way for me to insert a variable into the src attribute of my img tag like this: `<img alt="Avatar" src=`https://graph.facebook.com/${snAvatarSnuid}/picture`>`

I need assistance with passing a variable called snAvatarSnuid within the img src tag, specifically after facebook.com/ and before /picture as shown below: <img alt="Avatar" src=`https://graph.facebook.com/${snAvatarSnuid}/picture`> Note: 1) The ht ...

Email is displaying an empty POST state

I've implemented a contact form in Laravel that is supposed to send two emails - one as a confirmation email to the user and another to the sender. Despite not encountering any errors, the network tab displays a POST status without a specific status ...

What is the best way to preload all videos on my website and across different pages?

I specialize in creating video websites using HTML5 with the <video> tag. On my personal computer, the website transitions (fadeIn and fadeOut) smoothly. However, on my server, each page seems to take too long to load because the videos start preloa ...

Unable to alter a global variable while iterating through an angular.forEach loop

I've encountered a challenge while attempting to modify a global variable within an Angular.forEach loop. Although I can successfully update the variable within the loop, I'm struggling to maintain those changes when accessing the variable outsi ...

Switch ng-model in Angular to something different

I am looking to transform my own tag into a template <div><input .../><strong>text</strong></div> My goal is to have the same values in both inputs. Check out the plunker here If I change the scope from scope: {value:' ...

Having trouble with the `npm run dev` command in a Laravel project? You may be encountering a `TypeError: program.parseAsync is not

Recently, I integrated Vue.js into my ongoing Laravel project using npm to delve into front-end development with the framework. Following the installation, the instructions guided me to execute npm run dev in order to visualize the modifications made in . ...

Cannot render <Image> inside <Section> component

As a beginner in React, I am attempting to create an app following a tutorial. In my component, I utilized the figure tag but it's not showing up when inspecting element in Chrome. Here are the code snippets: The tutorial includes a div tag as a chil ...

AngularJS withCredentials Issue causing data not to be transmitted

When using AngularJS, I encountered an issue where the cookie/session was not being shared across domains for my Restful API in a subdomain. To address this problem in Angular, I added the following configuration: app.config(['$httpProvider', fu ...

Validating Firebase data for null values

Hey there, I'm currently working on a simple coding project but seems to be encountering some roadblocks. The main objective of the code is to determine if a username exists in the system or not. Here's a snippet of the data structure and codes ...

What is the difference in performance between using named functions versus anonymous functions in Node.js?

Currently, I am working on a Node.js app and was initially using anonymous functions for callbacks. However, after referring to the website callbackhell.com, I discovered that using named functions is considered best practice for coding. Despite switching ...

"Combining multiple attributes to target elements while excluding specific classes

My dilemma lies in the following selector that identifies all necessary elements along with an extra element containing the "formValue" class which I aim to omit $("[data-OriginalValue][data-OriginalValue!=''][data-TaskItemID]") ...

What are the advantages of choosing express.js over Ruby on Sinatra?

Currently brainstorming for a social app and contemplating the switch from my initial option, Sinatra/Ruby to express.js/nodejs. My main focus is on the abundance of open source projects in Ruby that can expedite development. Another major consideration i ...

Updating the Animation for Datepicker Closure

While using the date picker, I want it to match the width of the input text box. When closing the date picker, I prefer a smooth and single motion. However, after selecting a from and to date, the datepicker no longer closes smoothly. I have attempted sol ...

Is there a way to effectively incorporate window.clearInterval() into this javascript code to achieve the desired outcome

In my quest to create a pomodoro clock, I decided to experiment with window.setInterval() and its counterpart window.clearInterval before delving into actual coding. However, I've encountered an issue with getting window.clearInterval() to function as ...

Safari exceeded the maximum call stack size limit error

Has anyone else encountered the "Maximum call stack size exceeded" error when trying to fetch data from Firebase in Next.js? It seems to only occur on Safari based browsers, as the code works perfectly fine in Chrome based browsers under the same conditi ...

Prevent infinite scrolling with JavaScript AJAX when the response is empty

I am currently implementing the infinite scroll functionality on my website. Whenever the page reaches the bottom, an ajax call is triggered to fetch a new set of data. However, I'm unsure how to handle stopping the ajax call if there is no more data ...

What steps are involved in developing a quiz similar to this one?

Check out this interesting quiz: I noticed that in this quiz, when you answer a question, only that section refreshes instead of the entire page. How can I create a quiz like this? ...

Tips for ensuring proper function of bullets in glidejs

I am currently working on implementing glidejs as a slider for a website, but I am facing issues with the bullet navigation. The example on glidejs' website shows the bullets at the bottom of the slider (you can view it here: ). On my site, the bullet ...

Experiencing issues with the redirect button on the navigation bar of my website

Video: https://youtu.be/aOtayR8LOuc It is essential that when I click a button on my navigation bar, it will navigate to the correct page. However, since the same nav bar is present on each page, it sometimes tries to redirect to the current page multiple ...