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:

https://i.sstatic.net/RdUQW.png

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

I tried running the sample program from the website in mongoose, but I encountered a persistent error: "TypeError: fluffy.speak is not a function."

const mongoose = require('mongoose'); main().catch(err => console.log(err)); async function main() { await mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true }); console.log("Connection successfu ...

Integrate jQuery into a Vue.js 2 project using the expose-loader plugin

For my latest Vue.js project using the vue-cli, I attempted to import jQuery with expose-loader. Following the instructions in the official documentation, but unfortunately, I was not successful. Here are the steps I took: Installed jQuery and expose- ...

Having trouble with dynamic CSS not functioning properly when a checkbox is changed in Vue.js

I'm currently attempting to dynamically adjust the css styling of specific text within a span element by utilizing v-on:change on a checkbox. However, I am encountering an issue where the styling does not update as expected, and I am struggling to ide ...

Display/Collapse SELECT choices?

Consider this scenario : <select class="form-control" name="blah" ng-model="$ctrl.form.blah" ng-options="item.id as item.name group by item.etype | uppercase for item in $ctrl.opts"></select> My goal is to toggle the display of each GROUP b ...

Unable to render data in HTML page using Vue component

home.html: <body> <div id="app"> {{ message }} </div> <div id="counter"> {{ counter }} </div> <script type="text/javascript" src="https://cdn.js ...

Determining the height of dynamically rendered child elements in a React application

Looking for a way to dynamically adjust the heights of elements based on other element heights? Struggling with getting references to the "source" objects without ending up in an infinite loop? Here's what I've attempted so far. TimelineData cons ...

What is the best way to accurately establish a new name for the evolving scope

var tags_offset=[]; $scope.getRelations = function(id, ref, subRef=0){ tags_offset[ref+'-'+subRef]=0; $http.get( CONS.appHttp+ '/tags.php?ID='+id +'&ref='+ref +'&contentType='+subRe ...

Having trouble with installing Recharts through npm

When I try to install recharts using npm, I encounter the following error message in my console: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! ...

Ways to ensure that the $http.post api call waits for the response to be fully prepared

Below is the JavaScript code that I am using. When I click the button, it calls the function btnInitiateAPICall() which makes the first API call to get the number of users. However, my code does not wait for the first API call to finish before moving on ...

Tips for enhancing the appearance of a React component

I have a redux form that doesn't look great, and I would like to style it. However, my project uses modular CSS loaders. The styling currently looks like this: import styled from 'styled-components'; const Input = styled.input` color: #4 ...

Issue with Emitting from PrimeVue ConfirmDialog Inside accept Function

I'm currently utilizing the PrimeVue ConfirmService to initiate a dialog in a child component. My goal is to invoke a function in the parent component once the user confirms the dialog. Despite my attempts to use the emit method, it seems that the cal ...

Unable to properly display the message in Angular

<!DOCTYPE html> <html ng-app> <head> <script data-require="angular.js@*" data-semver="1.4.3" src="https://code.angularjs.org/1.4.3/angular.js"></script> <link rel="stylesheet" href="style.css" /> ...

The variable is unable to transfer successfully from JavaScript to PHP using ajax

I have a code that is designed to pass the values of all checked checkboxes to a PHP file in order to delete corresponding rows from a CSV file. The checkbox values are dynamic. <tr><td><span class="custom-checkbox"><input ty ...

Is there a way to properly access and interpret a .log extension file within a React component?

import React from "react"; import "./App.css"; function FileReaderComponent() { const readLogFile = () => { if (window.File && window.FileReader && window.FileList && window.Blob) { const preview = document.getElementByI ...

Replacing an array element in React.js

Here is a React.js code snippet where I am trying to utilize an array called distances from the file Constants.js in my Main.js file. Specifically, I want to replace the APT column in the sampleData with a suitable value from the array distances extracted ...

Fetching data in a post request seems to be causing an issue with FormData image being

I've implemented a profile picture file upload system with the following HTML: <form enctype="multipart/form-data" id="imageUpload" > <img id="profileImage" src="./images/avatar.png& ...

Issue with Google Adsense - adsbygoogle.push() error: Pages can only support one AdSense head tag. The additional tag will be disregarded

After adding my script tag to the navbar component, I encountered an error on my site during the next js build: Google Adsense error -adsbygoogle.push() error: Only one AdSense head tag supported per page. The second tag is ignored <Head> ...

What is the best way to search using vuefire?

import { collection, limit, query } from "firebase/firestore" import { useFirestore, useCollection } from "vuefire" const db = useFirestore() const messagesRef = collection(db, 'rooms/1/messages') const messages = useCollect ...

How can we use fetch to grab some data?

I put together an Express application quickly, here's how it looks: const express = require("express"); const app = express(); const port = 3000; app.get("/content/1/", (req, res) => res.send("Thinking about taking out a new loan? Call us today. ...

Is it possible to create a Facebook reveal tab using either Javascript or .NET?

As a developer who jumped into Facebook development just before the recent changes, I am feeling lost when it comes to building apps now. I see many questions similar to mine about creating fan-gating features using Javascript only. Is there an up-to-date ...