Firebase database is showing an undefined user id when interacting with Vuex

I have recently developed an e-commerce website and completed the registration process with email and password.

Now, I am looking to store user information such as email, full name, and timestamp in the database.

The screenshot below shows that I can view the user data in the Google Chrome Dev Console. https://i.sstatic.net/PTL3h.png

However, upon checking the Firebase database via the browser, I noticed that the user ID appears as undefined instead of the actual user ID.

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

Currently, I am at step 3 of the process:

  1. Add user data into the database

I am facing difficulties understanding why this issue is occurring and would appreciate any assistance you can provide.

Here is a snippet from my store/index.js file:


import fireApp from '@/plugins/firebase'

export const state = () => ({
    
    user: null,
    error: null,
    busy: false,
    jobDone: false
})

export const mutations = {
   
    setUser (state, payload) {
        state.user = payload
    },
    setError (state, payload) {
        state.error = payload
    },
    clearError (state, payload) {
        state.error = null
    },
    setBusy (state, payload) {
        state.busy = payload
    },
    setJobDone (state, payload) {
        state.jobDone = payload
    },
}

...
// Rest of the content remains unchanged
...

Answer №1

The reason for this is that the createUserWithEmailAndPassword() method returns a promise that resolves with a UserCredential object, not just a User.

To access the user, you should use the user property of the UserCredential, like so:

    let newUser = null
    fireApp.auth().createUserWithEmailAndPassword(payload.email, payload.password)
        .then(userCredential => {
            newUser = userCredential.user;
            //...

It's worth noting that you don't have to call fireApp.auth().currentUser to get the user.

When using the createUserWithEmailAndPassword() method, after successfully creating the user account, the user will automatically be signed in to your application. Simply retrieve the user using userCredential.user as shown above.


Additionally, keep in mind that the updateProfile() method is asynchronous and returns a Promise, which should be integrated into your promises chain.

Here's an example implementation (not tested):

  signUpUser({commit}, payload) {
      commit('setBusy', true)
      commit('clearError')
      //1.Signup new user.
      //2.Update firebase user profile & set local user data.
      //3.Add user data into database
      //4.Attach user to consumer group
      let user = null;
      fireApp.auth().createUserWithEmailAndPassword(payload.email, payload.password)
          .then(userCredential => {
              user = userCredential.user;
              return user.updateProfile({ displayName: payload.fullname });
          })
          .then(() => {
              const currentUser = {
                  id: user.uid,
                  email: payload.email,
                  name: payload.fullname,
                  role: 'consumer'
              }
              console.log('USER', currentUser)
              commit('setUser', currentUser)
              const userData = {
                  email: payload.email,
                  fullname: payload.fullname,
                  createdAt: new Date().toISOString()
              }

              return fireApp.database().ref(`users/${user.uid}`).set(userData)
          })
          .then(() => {
              commit('setJobDone', true)
              commit('setBusy', false)
          })
          .catch(error => {
              commit('setBusy', false)
              commit('setError', 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

Tips for Deactivating One Button While Allowing Others to Remain Active

Whenever the $order_status is marked as Accepted, only the button labeled Accept should be disabled. If the $order_status changes to Dispatched, then the button that should be disabled is labeled as Sent. However, if the status is Cancelled, then the butto ...

Is the Angular $watch function able to track changes on an object's prototype members as well?

I have encountered a challenge with a tree structure implemented in Javascript which has circular references. The objects in the structure contain an array of children, but these children also need to reference their parent for deletion purposes. To monit ...

Dynamically Loading External JavaScript Files Depending on User Input

Looking for guidance on how to dynamically load a single javascript file out of several options based on user input in an HTML code. Any suggestions on how to achieve this task? Thank you! ...

Vuetify's V-Layout and V-Flex components are essential for creating

I am trying to make the textbox occupy 6 columns on screens larger than sm and 12 columns on mobile devices. Even after using the vuetify grid, it is not behaving as I expected. This is the code I have: <v-card-text> <v-layout warp> ...

Error with Expression Engine: PHP function cannot be executed

I have been attempting to execute a PHP Script with ExpressionEngine tags using Ajax on my webpage. I followed the documentation and set up the PHP script accordingly, but it appears that I am unable to call the function in the PHP script. There must be so ...

the integration of shapes in three.js is malfunctioning

There has been a dynamic change in the path. The previous render function was as follows (where LENGTH, getPosition(), RADIUS, MATERIAL, and SCENE have already been set) var prevPosition = getPosition(); for(var i =0; i < LENGTH; i++) { drawPath(g ...

Creating a customized style for a child styled-component within a parent component

In my attempt to style a nested <Input /> component using styled-components, I find myself facing a challenge. The nested input is being utilized within a different component that displays a dropdown when typing. My goal is to apply padding-left: 3re ...

Is it possible to refresh an iframe with PHP once a certain condition is satisfied?

I have a situation with two pages - one is my PHP script and the other is an HTML page containing two iframes. > <html> > > <iframe name=1></iframe> <iframe name=2></iframe> > > </html> Currently, ifram ...

Steps for accessing an ASP.NET control using getElementById

I am encountering an issue with locating an element on my webpage. <asp:Button ID="buttonToFind" runat="server" OnClick="SomeProcess" /> While using JavaScript, I am attempting to find this control with the following code: document.getElementById( ...

Setting up Vue/Vite configuration for a multi-page application with multiple entry and output files

I am trying to set up Vue/Vite to handle multiple input files and generate separate output bundles for each one. Each bundle represents a different route and view within my project, utilizing the same components, styles, data models, and supporting service ...

Retrieve information on input type hidden using Vue.js

Every time I attempt to retrieve the data "Id" from my list, the script returns the wrong Id. I specifically need the Id from that field, but the value returned is incorrect. <input type="hidden" name="Id" id="Id" v-mode="todo.Id"> I have resorte ...

Refreshing is not necessary when submitting a form using Ajax to post data

Initially, I find myself torn between using method or type, where if I define the method in the form, do I still need to define it in the ajax call? If not, why does ajax return undefined in the console? Furthermore, the code below triggers a 405 POST met ...

Function that is asynchronous and returns an undefined variable

While experimenting with an async function, I encountered an issue where it returns a boolean value as undefined. checkIfEmptyDb = async => { var ref = firebase.database().ref("dynamicDb"); ref.once("value").then(snapshot => { const a ...

Using Vuex Namespaces to Manage State in a Store

I've encountered a challenge in my project involving a complex Vuex store. This store is responsible for saving filter input values and transforming them into filters that can be used to query the backend later on. The issue arises when I need to appl ...

Nativescript apps are unable to utilize Node modules

I am currently facing an issue with integrating multiple plugins into my Nativescript application. The computed path to locate these installed plugins appears to be incorrect, and I am unable to locate any guidance on how to rectify this issue. Is there a ...

The onclick button in React is not triggering

I am currently working on a component that processes card clicks and redirects users to a previous route, however, the OnClick function does not seem to be functioning properly. I'm trying to pinpoint where I might be going wrong. function Character ...

ReactJS - When a click event is attached to a list of elements, it triggers the "click" event for each individual element in the list

I have a group of li elements under a ul element (as shown below), and when I click on any li element, I want it to add a class name to just that specific li element. However, currently when I click on one li element, the click event is triggered for all l ...

Improving methods for handling AJAX requests in PHP

I am facing an issue with a JavaScript file that sends an AJAX request to a PHP file to fetch data from a database. When the PHP file does not find any record based on the query, it returns a message like "no match found" instead of a JSON object in the ...

Is it possible to exchange meshes across different scenes in three.js?

Can meshes or geometry be shared across scenes? I am facing an issue where I have multiple scenes that require the same large meshes, but attempting to share these meshes between scenes results in WebGL context errors. It seems like certain variables are ...