webknit
webknit

Reputation: 159

Vue.js/vuex getters error before state rendered

Using webpack vue template and vuex.I have a mutation in my store

const mutations = {
addWeekDataList(state, a) {
    state.weekDataList = a;
},}

which is being committed inside an ajax request inside a component

axios.get('URL').then(function (response) {
let weekDataList = _.values(response);
that.$store.commit('addWeekDataList', weekDataList);});

I then have a getter in my store

const getters = {
getWeekRunData: state => {
    return state.weekDataList[state.currentWeek].filter(activity => activity.type === 'Run' );
},
}

Which are called inside a component's computed property

computed: {
    weekRunDataTime: function() {
        return Utils.convertSecsToHrsMins(Utils.addFields(this.weekRunData, 'moving_time'));
    },
    ...mapGetters({
        weekRunData: 'getWeekRunData',
    }),
},

There are no errors so far, the computed properties return their data when it's ready. However as soon as i do the following inside the component template I get an error...

{{ weekRunDataTime }}
TypeError: state.weekDataList[state.currentWeek] is undefined

The computed property, and then the {{ weekRunDataTime }}, will eventually render but the error still shows initially, how do i get around this? Ensuring the getters only run once the data is available?

Upvotes: 3

Views: 2710

Answers (2)

Rahul Singh
Rahul Singh

Reputation: 209

Adding initial data will resolve the issue

const state = {
      user: something
    };

Upvotes: 1

webknit
webknit

Reputation: 159

The error is because state.weekDataList isn't loaded so state.weekDataList[0] would be undefined. I came across two solutions, once of which was from @AmreshVenugopal. One was to add a sample data set into the array and the second, and most preferred, was to add an if statement into the getter, so that it only loads once the data is loaded. Everything now loads fine with no errors.

const getters = {
getWeekRunData: state => {
    if(state.weekDataList.length) return state.weekDataList[state.currentWeek].filter(activity => activity.type === 'Run' );
}}

Upvotes: 2

Related Questions