Search code examples
javascriptvue.jsvuex

Vue data being stored in vuex but not displaying in the UI


I am trying to get some plan data to show up in my Vue application. The data is loaded via an API I have running locally. I have figured out how to add the data to the store/vuex and vue dev tools shows it is good however I am unable to see the data in the UI. I am looking for help on solving why the data is not showing in the UI.

In my plans.vue I just do a for loop over the plans data and it works if I manually put the data into the array so somewhere between the store and the data prop it is broken.

store.js

state: {
 plans: []
}
mutations: {
  loadPlans(state, plans) {
     state.plans = plans
 }
},
getters: {
    loadPlans(state) {
      return state.plans
    },
}

plans.vue

created() {
        PageOptions.pageEmpty = true;
        this.$store.dispatch('loadPlans')
    },
    data() {
        return {
            plans: this.$store.getters.loadPlans,
        }
    },

This is striped down to include just the code used for this issue, there is a ton more code that isn't related to this.


Solution

  • Try with something like this:

    store.js

    state: {
      plans: []
    },
    getters: {
      loadedPlans(state) {
        return state.plans
      },
    },
    mutations: {
      setPlans(state, plans) {
        state.plans = plans
      }
    },
    actions: {
      async loadPlans({commit}) {
        await this.$axios.get('http://localhost/api/plans', function(response) {
          commit('setPlans', response.data)
        })
      }
    }
    

    plans.vue

    async created() {
      await this.$store.dispatch('loadPlans')
    },
    computed: {
      myPlans() {
        return this.$store.getters.loadedPlans
      }
    }