Yohei Umezu
Yohei Umezu

Reputation: 431

Vuex and firebase: The user id is undefined in the firebase database

I am creating an e-commerce web site.

Now I finished creating the new account with email and password.

And I want to insert the user email, full name, and timestamp in the database.

As you can see in the picture below, I could see the USER data in the google chrome dev console. enter image description here

But when I checked the firebase database in the browser, I cannot see the user id. And instead, I see undefined in the user id column.

enter image description here

Now I am on the step3 process.

  1. Add user data into database

I cannot figure out why it's happening, so I hope you can help me out.

This is 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
    },
}

export const actions = {
   
    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 newUser = null
        fireApp.auth().createUserWithEmailAndPassword(payload.email, payload.password)
            .then(user => {
                newUser = user
                var user = fireApp.auth().currentUser;
                user.updateProfile({ displayName: payload.fullname })
                const currentUser = {
                    id: user.uid,
                    email: payload.email,
                    name: payload.fullname,
                    role: 'consumer'
                }
                console.log('USER', currentUser)
                commit('setUser', currentUser)
            })
            .then(() => {
                const userData = {
                    email: payload.email,
                    fullname: payload.fullname,
                    createdAt: new Date().toISOString()
                }
                
                fireApp.database().ref(`users/${newUser.uid}`).set(userData)
            })
            .then(() => {
                commit('setJobDone', true)
                commit('setBusy', false)
            })
            .catch(error => {
                commit('setBusy', false)
                commit('setError', error)
            })
    }
}

export const getters = {
    
    user (state) {
        return state.user
    },
    error (state) {
        return state.error
    },
    busy (state) {
        return state.busy
    },
    jobDone (state) {
        return state.jobDone
    }
}



  

Upvotes: 0

Views: 285

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83093

This is because the promise returned by createUserWithEmailAndPassword() method resolves with an UserCredential object and not with a User one.

You should use the user property of the UserCredential, as follows:

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

Note also that you don't need to call fireApp.auth().currentUser to get the user.

When using the createUserWithEmailAndPassword() method, on successful creation of the user account, this user will also be signed in to your application, so just get the user with userCredential.user, as explained above.


In addition, note that the updateProfile() method is asynchronous and returns a Promise, which you need to include in your promises chain.

So the following should do the trick (untested):

  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)
          })
  }

Upvotes: 2

Related Questions