Reputation: 409
I'm trying to store the accessToken that comes back from Firebase into the Vuex store in my Vue project when I run the code I get the following error:
Uncaught TypeError: Cannot read property '$store' of undefined
It looks like it's not picking up store.js in the code below, any ideas why that might be?
Thanks
Login.vue
mounted: function() {
Firebase.auth.onAuthStateChanged( user => {
if (user) {
user.getIdToken().then(function(idToken) {
this.$store.commit('setStoreToken', idToken)
return idToken
});
}
else {
.
.
.
}
store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
loggedIn: false,
accessToken: '',
},
mutations: {
loggedIn () {
this.state.loggedIn = true
},
loggedOut () {
this.state.loggedIn = false
},
setStoreToken(state, accessToken) {
state.accessToken = accessToken
},
},
getters: {
getAccessToken: state => {
return state.accessToken
}
},
})
main.js
import store from './store.js'
new Vue({
store,
router,
render: h => h(App),
}).$mount('#app')
Upvotes: 0
Views: 625
Reputation: 14904
My guess:
user.getIdToken().then(function(idToken) {
this.$store.commit('setStoreToken', idToken)
return idToken
});
You dont use an arrow function, that means that this
is binded to the function itself you can either use an arrow function or you create a variable infront of it like this const self = this
user.getIdToken().then((idToken)=>{
this.$store.commit('setStoreToken', idToken)
return idToken
});
Or you do it like this:
const self = this;
user.getIdToken().then(function(idToken) {
self.$store.commit('setStoreToken', idToken)
return idToken
});
Upvotes: 3