Vue.js / vuex ajax update components with ajax state

I am using vue webpack template with vuex and I am mostly having problems with components not updating with state.

I have a store

const state = {
  userData: {},
}

      

In my application I have a method

methods: {

    addUserData: function() {
        const that = this;
        axios.get('URL').then(function (response) { 

            let obj = response.data;
            that.$store.commit('addUserData', {obj});

        }); 
    },

      

which I call when it is installed

mounted () {

    this.addUserData();

},

      

What gets updated with mutation

const mutations = {
addUserData(state, {obj}) {
    state.userData = obj;
},}

      

Everything is in order, here the data is stored in the store. But then I have a component that is not working as it does not wait for ajax to finish loading and will not be attached in any way. I may be doing it wrong here, but basically in my component I have

data () {
    return {
        weekData : {
            weekDataList: []....

methods: {

    tester: function(a) {

        // Sorting the userdata using lowdash
        this.weekData.weekDataList = _.values(this.$store.state.userData);

    },

},

      

I call it the same as before

mounted () {

    this.tester();

},

      

The problem is that this.weekData.weekDataList always returns an empty array because the user data in the store could not be executed. I have dozens of methods doing various calculations, all based on this one array, so if they fail, they all fail.

Perhaps my approach is wrong, but ideally I would like the data attributes to be updated after the store is updated? I tried to do it with computed properties and worked fine with {{whatever}} but didn't know how to update the component data.

+3


source to share


1 answer


you were on the right track. Computable properties are definitely the way to go. In your current situation, your component knows nothing about the store in any reactive form. You have a function that tries to read data at any point and the data may be correct.

So, first of all if the component is nested within the parent as it appears to this.$store

point to the same store. Then you should try to use the required value as a property, so it is responsive.

computed: {
  userData: function () {
     return this.$store.state.userData
  }
}

      

and while you're at it, also put the week data in the computed properties:



computed: {
  userData: function () {
     return this.$store.state.userData
  },
  weekData: function () {
    return {
      weekDataList: _.values(this.userData)
    }
  }
}

      

In this way, all data will be responsive and weekData

updated accordingly.

Hope this helps, and in general, when you are already using Webpack, I would consider starting using ES6 syntax as it makes things more readable and some parts are a little cleaner :)

+1


source







All Articles