I have a stored userProfile
in the Vuex
state in order to access it throughout my project. However, when I try to use it in the created()
hook, the profile is not loaded yet during the initial page load. Although the object exists, it does not contain any data at that moment. Interestingly, accessing it later on, such as by clicking a button, works perfectly fine.
Is there a way to wait for the data to finish loading?
This is how the userProfile
is set in Vuex
:
mutations: {
setUserProfile(state, val){
state.userProfile = val
}
},
actions: {
async fetchUserProfile({ commit }, user) {
// fetch user profile
const userProfile = await fb.teachersCollection.doc(user.uid).get()
// set user profile in state
commit('setUserProfile', userProfile.data())
},
}
Below is where I am trying to access it:
<template>
<div>
<h1>Test</h1>
{{userProfile.firstname}}
{{institute}}
</div>
</template>
<script>
import {mapState} from 'vuex';
export default {
data() {
return {
institute: "",
}
},
computed: {
...mapState(['userProfile']),
},
created(){
this.getInstitute();
},
methods: {
async getInstitute() {
console.log(this.userProfile); //is here still empty at initial page load
const institueDoc = await this.userProfile.institute.get();
if (institueDoc.exists) {
this.institute = institueDoc.name;
} else {
console.log('dosnt exists')
}
}
}
}
</script>
Upon logging in the console, I discovered that the issue lies in the sequence of code execution. First, the method getInstitute
runs, followed by the action
, and then the mutation
.
I attempted to introduce a loaded
parameter and experimented with await
to resolve this problem, but nothing has provided a solution.