Order of Execution for VueJS dispatch function is causing an issue


I’m trying to display a list of announcements (retrieved from API) on the page. I’m using Vuex store and I have a state called announcements. I also want this list to be updated every time the user refreshes/enters the page. So I used lifecycle hooks, particularly the mounted().
I have a dispatch function that takes a club ID as a parameter. The issue is that I try to access the announcement array in the Vue component, it is one "step" behind the version in the Vuex store.

The Following is in the Vue component ClubDetails.vue

  name: "ClubDetails",
  data(){
    console.log("inside data")
    return {
      club_id: this.$route.params.clubID,
      announcements: this.$store.state.ClubDetails.announcements
    }
  },
  mounted() {
      this.$store.dispatch('ClubDetails/getAnnouncements', this.club_id)
      console.log("After dispatch function")
  },

This is my store ClubDetails.js

    namespaced: true,
    state: {
        announcements: [],
    },
    mutations: {
        setAnnouncements(state, newArr) {
            state.announcements = newArr
            console.log("Inside Mutation")
        },
    },
    actions: {
        async getAnnouncements({ commit, state }, club) {
            const params = new URLSearchParams([
                ['clubId', club]
            ]);
            await axios.get("http://127.0.0.1:8000/api/announcements", { params }).then(res => {
                console.log("inside dispatch function")
                commit('setAnnouncements', res.data)

            }).catch(err => {
                console.log(err)
            })
        },
    },
    getters: {
        getAllAnnouncements(state) {
            return state.announcements;
        }
    },
}; 

After the print statements, the order of execution is not what i expected

I expected the order to be like this: inside data -> inside dispatch -> inside mutation -> after dispatch.

Another issue is that when I refresh the page, i expected mounted() to be called again and the array would be updated and displayed again, but when refreshing all the contents of the array disappear

Source: JavaSript – Stack Overflow

November 27, 2021
Category : News
Tags: javascript | vue-component | Vue.js | vuex | vuex-modules

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.