I'm using Vuex to try manage application-level data. I fetch the data, using axios, then propogate that data to data variables in a component. Nothing complicated.
My store looks like this
// store.js
// appropriate imports and such
export const store = new Vuex.Store({
state: {
var: []
},
actions:{
getData(context){
axios.get('/endpoint').then(function(response){
context.state.var = res.data.value1;
console.log("action in store.js run");
//appropriate brackets,etc below
I then dispatch this action in my app.js
//appropriate imports and such above
const app = new Vue({
el: '#app',
store: store,
created() {
this.$store.dispatch('getRightSidebar')
console.log("action dispatched")
}
});
I use the created lifecycle hook to ensure this action gets dispatched before the component is mounted. Surely, at this point two messages should be logged to the console. One message from the created lifestyle hook and another from the actual action being dispatched. However, when I run the application only the former message is logged. Surely, when the action is dispacthed, the actual method/request me be called/executed.
Now, when I print the values of the state variables, from within the mounted lifecycle hook of the component, they're undefined. However, if I print the state it logs the object with the appropriate data
///component.js
mounted() {
console.log("component mounted")
console.log(this.$store.state.var) // undefined
console.log(this.$store.state) // Obeject with the appropriate data
}
So on one hand it seems to dispatch the action, but when I try to access individual objects from the state, it craps itself. Is there something wrong with the way I'm trying to access objects within the state?
you need to "wait" for getData
promise to resolve
when created() hook runs there can be no data
export const store = new Vuex.Store({
state: {
var: []
},
actions:{
getRightSidebar(context){
// must return Promise to subscribe to it!
return axios.get('/endpoint').then(function(response){
context.state.var = res.data.value1;
console.log("action in store.js run");
const app = new Vue({
el: '#app',
store: store,
data: {
isLoading: true
},
async mounted() {
await this.$store.dispatch('getRightSidebar')
// after this there is gonna be some data
this.isLoading = false
}
})
<template>
<div>
<div v-if='isLoading'>loading...</div>
<div v-else>{{$store.state.yourvariable}}</div>
</div>
</template>