I am currently working on an application that integrates Vue.js and Firebase.
So far, I have successfully implemented the login functionality using email/password and can store the user information from firebase.auth() in the state.currentUser of Vue.js.
However, according to Firebase guidelines, there is more data stored under '/users' reference. For example, /users/uid
I would like to also retrieve this data into the vuex store (state.userMeta) so that I can utilize it throughout the site. The issue is that it does not work after a refresh. If I do not refresh, logout and then log back in, it populates the state correctly.
Your assistance with this matter would be greatly appreciated!
James
auth.js
import { auth, db } from '@/config/database'
import store from '@/vuex/store'
const init = function init () {
auth.onAuthStateChanged((user) => {
if (user) {
store.dispatch('setUser', user)
} else {
// User is signed out.
store.dispatch('setUser', null)
}
}, (error) => {
console.log(error)
})
}
export { init }
store.js
import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'
import { db } from '@/config/database'
Vue.use(Vuex)
const state = {
currentUser: null,
userMeta: null
}
const mutations = {
SET_USER (state, user) {
if (user) {
state.currentUser = user
db.ref('users/' + user.uid).on('value', function (s) {
state.userMeta = s.val()
})
} else {
state.currentUser = null
state.userMeta = null
}
}
}
const actions = {
setUser ({commit}, user) {
commit('SET_USER', user)
}
}
const getters = {
currentUser: state => state.currentUser
}
export default new Vuex.Store({
state,
mutations,
actions,
getters,
plugins: [createPersistedState()]
})
App.vue
<template>
<div id="app">
<router-view></router-view>
</div>
</template>
<script>
import * as auth from '@/config/auth'
const initApp = function initApp () {
auth.init()
}
export default {
name: 'app',
created: initApp
}
</script>
<style lang="scss" src="./assets/sass/style.scss"></style>
main.js
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import VueFire from 'vuefire'
import router from './router'
Vue.config.productionTip = false
Vue.use(VueFire)
import store from '@/vuex/store'
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
template: '<App/>',
components: { App }
})