Search code examples
vue.jsvuejs2vuex

How to call an api before loading the DOM in Store Vuex?


I want to Execute a function before loading the DOM to fetch the data from an API, I know that in vue it is with before Create but how do I do it in the VUEX store?


Solution

  • In VueX you execute asynchronous code in "actions". So you create an action and call it either from the beforeCreate lifecycle hook or wherever you want to put it.

    To call an action you can either use this.$store.dispatch('getMatches') or you can map an action to your components method block:

    methods: {
      ...mapActions([
        'getMatches'
      ])
    },
    beforeCreate() {
      this.getMatches();
    }
    

    Usually actions also start with lowercase letters, since they're methods.