Reputation: 603
I would like to get access to the state
property currentUser
of vuex
in user.js
to use it in auth.js
but it doesn't work if I write: store.state.currentUser.uid ===
...
And I get this error:
Cannot read property 'state' of undefined.
What is there missing in the code?
the tree:
src
store
user
|>user.js
|>mutations.js
index.js
auth.js
user.js:
const state = {
profile: {},
loggedIn: false,
currentUser: null,
userProfile: {}
}
export default {
namespaced: true,
state
}
auth.js:
import store from './store'
const fb = require('./firebaseConfig.js')
fb.auth.onAuthStateChanged(user => {
if (user) {
fb.postsCollection.orderBy('createdOn', 'desc').onSnapshot(querySnapshot => {
let createdByCurrentUser
if (querySnapshot.docs.length) {
createdByCurrentUser = store.state.currentUser.uid ===
querySnapshot.docChanges()[0].doc.data().userId ? 'Yes' : 'No'
console.log(createdByCurrentUser)
}
})
}
})
index.js
import Vue from 'vue'
import Vuex from 'vuex'
import user from '@/store/user'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
awesome: true
},
modules: {
user
}
})
export default store
Upvotes: 3
Views: 5017
Reputation: 1451
You need to use the getters
, take a look in the doc
getters.js
export default {
currentUser
}
function currentUser({ currentUser }) {
return currentUser;
}
user.js
import getters from './getters'
export default {
namespaced: true,
state: {
profile: {},
loggedIn: false,
currentUser: null,
userProfile: {}
},
getters
}
auth.js
import store from './store';
const currentUser = store.getters['user/currentUser'];
Because you namespaced the module, you have to use it's name as a prefix to access the getter function
Upvotes: 5