简体   繁体   中英

Vuex and Firebase, store additional user info

I have a function where i'm creating a user with Firebase and Vuex, and want to store some additional information about the user.

When I create a user, I run the code below, where payload contains email, password and name as an object. This is in actions in vuex.

signUserUp ({ commit }, payload) {
  firebase.auth().createUserWithEmailAndPassword(payload.email, payload.password)
    .then((u) => {
      firebase.database().ref('users/' + u.user.uid).set({
        name: payload.name,
        email: payload.email,
        registeredTools: []
      })
      // This commit('setUser')... sets the local data (local state).
      commit('setUser', { id: u.user.uid, name: payload.name, email: payload.email, registeredTools: [] })
    })
    .catch(
      error => {
        console.log(error)
      }
    )
},

The user gets created, and my database store data like name and email, (I will soon be adding some new datafields to the user. )

This workes as expected. I have an autoSignIn-function which updates the local user when refreshing or closing/opening the browser. My problem occurs when i'm getting the userdata, and try to merge the object from the auth-function (only ID and email), with the the object from my database, which currently, only holds the name of the user.

-Here is my attempt:

autoSignIn ({ commit }, payload) {
  const userDataFromAuth = { id: payload.uid, email: payload.email }
  firebase.database().ref('users/' + payload.uid).once('value')
    .then((data) => {
      const userDataFromDatabase = []
      const obj = data.val()
      for (let key in obj) {
        userDataFromDatabase.push({
          name: obj[key].name
        })
      }
      var userData = {...userDataFromAuth, ...userDataFromDatabase}
      console.log(userData)
      commit('setUser', userData)
    })
},

Any ideas on how I might do this?

This is a pretty good solution to the problem:

autoSignIn ({ commit }, payload) {
  const userDataFromAuth = { id: payload.uid, email: payload.email }
  firebase.database().ref('users/' + payload.uid).once('value')
    .then((data) => {
      const userDataFromDatabase = { name: data.child('name').val() }
      const userData = { ...userDataFromAuth, ...userDataFromDatabase }
      commit('setUser', userData)
    })
},

First, we get the data from the auth-function of firebase (which contains id and email). And then we get the data under 'users/' + payload.uid (id), and then we merge those two javascript objects, and store them in the store.users (vuex's local store of data), which we can use throughout our application. Please feel free to ask questions or suggestions for improvements.

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