I am encountering an issue with getters that are returning the initial state (an empty array).
In my component, I have a method called created
that sets the axios call result into the state.
created() {this.$store.dispatch("SET_STORIES");},
I am using mapGetters in the computed section:
computed: {
...mapGetters(["GET_STORIES"])
},
There is also a method to get the state:
methods: {
stories() {
return this.$store.getters.GET_STORIES;
}
}
The mounted()
hook is displaying an empty array:
mounted() {
console.log("stories", this.$store.getters.GET_STORIES);
},
store.js
import Vue from "vue";
import Vuex from "vuex";
import axios from "axios";
import VueAxios from "vue-axios";
import chunk from "lodash/chunk";
Vue.use(Vuex, VueAxios, axios);
export default new Vuex.Store({
state: {
stories: [],
twoChunkStories: []
},
getters: {
GET_STORIES: state => {
return state.stories;
}
},
mutations: {
SET_STORIES(state, stories) {
state.stories = stories;
},
SET_CHUNKED_STORIES(state, stories) {
state.twoChunkStories= stories;
},
},
actions: {
SET_STORIES: async ({ commit }) => {
const options = {
headers: {
"Content-Type": "application/json"
}
};
let { data } = await axios.get(
"https://api.example.com/get.json",
options
);
if (data.meta.code === 200) {
let storiesArray = data.data.stories;
let chunkSize = 2;
commit("SET_STORIES", storiesArray);
let chunkedArray = chunk(storiesArray, chunkSize);
commit("SET_CHUNKED_STORIES", chunkedArray);
}
}
}
});
I am trying to figure out how to make an asynchronous axios call to set the state onload in the earliest possible lifecycle hook (which I thought was created()
) and be ready to be accessed on mounted. There seems to be an issue with how I am handling the asynchronous operation over the getters, but I'm unsure of what exactly it is.