简体   繁体   中英

$fireDb undefined in Nuxt Fire / Firebase Vuex

I'm using Nuxt JS 2.9.2 to build a Javascript application. It features a Firebase integration via the Nuxt Fire module, and Vuex to handle state management and authentication.

I have the project set up, and I'm able to create users, log them in and log them out.

I'm trying to now set some data along with the user ID in Firebase, and am getting an $fireDb undefined error, even though the user is still being created (without any information set):

function createNewAccount (user) {
  const databaseRef = this.$fireDb.ref(`accounts/${user.uid}`)
  return databaseRef.set({
    displayName: 'Test Display Name', // use part of the email as a username
    email: 'My Test Email',
    image: 'Some Image' // supply a default profile image for all users
  })
}

export const actions = {

  /*
   * Create a user
   */
  createUser ({commit}, payload) {
    this.$fireAuth.createUserWithEmailAndPassword(payload.email, payload.password).then(function({user}) {
      commit('localStorage/setUser', { email: payload.email }, { root: true })
      createNewAccount(user)
    }).catch(function(error) {
      console.log('error registering' + error)
    });
  }
}

I'm trying to figure out why this.$fireDb is undefined? I've tried following the documentation, but this part seems broken?

https://github.com/lupas/nuxt-fire#usage

You are trying to access .this outside of the store in your createNewAccount() function.

You have access to this.$fireDb in your store, your .vue files and nuxt plugins, but not automatically outside of that scope.

So you can either for example move the function inside a store action like so:

export const actions = {
  /*
   * Create a user
   */
  createUser({ commit, dispatch }, payload) {
    this.$fireAuth
      .createUserWithEmailAndPassword(payload.email, payload.password)
      .then(function({ user }) {
        commit('localStorage/setUser', { email: payload.email }, { root: true })
        dispatch('createNewAccount', true) // CHANGED THIS
      })
      .catch(function(error) {
        console.log('error registering' + error)
      })
  },

  createNewAccount({ commit }, user) {
    const databaseRef = this.$fireDb.ref(`accounts/${user.uid}`)
    return databaseRef.set({
      displayName: 'Test Display Name', // use part of the email as a username
      email: 'My Test Email',
      image: 'Some Image' // supply a default profile image for all users
    })
  }
}

or run in anywhere else in your app where you have access to the nuxt conext through .this.

Hope that helps :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM