I am attempting to do a set of a variable in my beforeCreate() for a component and then in the created() get that variable. Essentially I need to set the variable in my store then get that variable. My created calls an action that runs an axios promise that commits the data to the state, and I have a getter in the store that I want to call in my created() to get that data.
I know I am getting the correct data back from my promise as I can see it in my console log, I just cant seem to get that data from my getter.
It doesn't seem to want to work, and I think it has to do with the fact that axios has not returned the promise yet? How can I ensure that my created() waits until the axios promise has been returned in beforeCreate()?
Sample code
..... Component....
data(){
return{currentUser: null}
},
beforeCreate(){
this.$store.dispatch('users/setCurrent')
},
created(){
this.currentUser = this.$store.getters['users/current'].displayname
}
......Store.....
export const state = () => ({
current: {}
});
export const mutations ={
setCurrent: (state, c) => (state.current = c)
}
export const getter = {
current: state => state.current
}
export const actions = {
setCurrent({commit, dispatch, rootState}){
this.$axios.$get('/api/user/current', {headers: rootState.sessionUser.current})
.then(res => {
console.log(res)
commit("setCurrent" res)
})
}
Try to wait for response in your actions:
export const actions = {
async setCurrent({commit, dispatch, rootState}){
await this.$axios.$get('/api/user/current', {headers: rootState.sessionUser.current})
.then(res => {
console.log(res)
commit("setCurrent" res)
})
}
and then in created or mounted hook :
async created() {
await this.$store.dispatch('users/setCurrent')
this.currentUser = this.$store.getters['users/current'].displayname
}