javascript - Check logged user in firebase with Nuxt.js middleware -
i've built middleware nuxt app.
import api '~/api/api.js' export default function ({router, store}) { return api.auth().onauthstatechanged(function (user) { store.state.user = user if (user) { } else { } }) }
now, how access user object? when i'm doing normal component it's working correctly. passing store simple string works, other action no, there need of kind of promise? thx help.
from vuex documents:
the way change state in vuex store committing mutation. vuex mutations similar events: each mutation has string type , handler. handler function perform actual state modifications (documentation link)
mutations trigger dom update in vue, committing mutation, reactive elements updated, whereas directly manipulating state sending string not cause reactive update. vuex docs:
since vuex store's state made reactive vue, when mutate state, vue components observing state update automatically
the section entitled "mutations follow vue's reactivity rules" has more detailed run-down on this.
the caveat here mutations work synchronous data. if have async data, vuex actions of assistance - can perform mutation , handle asynchronous events.
in absence of further example code, difficult asses whether there other issues @ play here, have included sample store file works exact scenario. whilst not nuxt-specific, principle same:
// store.js import vue 'vue' import vuex 'vuex' vue.use(vuex) const state = { user: {}, files: [], token: '' } const mutations = { logout (state) { state.user = null }, setuser (state, user) { state.user = user }, settoken (state, token) { state.token = token } } const actions = { logout: ({ commit }) => commit('logout'), setuser: ({ commit }, user) => commit('setuser', user), settoken: ({ commit }, token) => commit('settoken', token) } const getters = { user: state => state.user, token: state => state.token, files: state => state.files } export default new vuex.store({ state, getters, actions, mutations })
then in module:
import store '@/store' import { mapgetters } 'vuex' api.auth().onauthstatechanged(function (user) { store.dispatch('setuser', user) // .dispatch triggers action, handling async evt if (user) { } else { } }) export default { // mapgetters maps getters allowing this.user in script, or {{ user }} in template computed: mapgetters([ 'user', 'files' ]) }
Comments
Post a Comment