0
You need to dispatch the action in the created method, where you create your vue instance. If the action is dispatched in a component, the store is only injected after the component is mounted. The data will only load after mounting the component which means component(s) that need to read the data, will have access to it, however the data in the state will be undefined on load.
export const store = new Vuex.Store({
state: {
sample2 : [], // undefined
sample3: [] // undefined
},
getters:{
},
actions:{
getData(context){
axios.get('/endpoint').then(function(response){
context.state.sample2 = response.data.sample2data;
context.state.sample3 = response.data.sample3data;
}
);
}
},
mutations:{
}
});
The below ensures that action is dispatched before mounting any components, and therefore the components will be able to read the state after the action has properly set the values
import {store} from 'path/to/store/';
new Vue({
el: '#app',
computed:,
store: store,
created() {
this.$store.dispatch('getData') // dispatch loading
}
})
0
In the mounted
method of your App.js
you can do
mounted() {
this.$store.dispatch('getData')
}
Source:stackexchange.com