user7021169
user7021169

Reputation:

Vue - call async action only after first one has finished

I need to call 2 actions from inside my component, but the second should only start after the first one has 100% finished it's job.

I'm trying this but it doesn't work

mounted() {
    this.$store.dispatch('coinModule/loadApiCoins')
        .then(() => {
            this.$store.dispatch('coinModule/loadUserCoins')
        })
        .catch(error => {
            console.log(error)
        });
},

and the 2 actions are these

    loadApiCoins({ commit, dispatch, rootGetters }) {
        Vue.axios({
                method: 'get',
                url: 'https://api.coinmarketcap.com/v1/ticker/',
                transformRequest: [(data, headers) => {
                    delete headers.common.Authorization
                    return data
                }]
            })
            .then(response => { commit('SET_API_COINS', response.data) })
            .catch(error => { console.log(error) })
    },

    loadUserCoins({ commit, dispatch, rootGetters }) {
        Vue.axios.get('http://127.0.0.1:8000/api/coins/')
            .then(response => {
                commit('SET_USER_COINS', response.data)
                commit('SET_USER_PORTFOLIO_OVERVIEW')
            })
            .catch(error => { console.log(error) })
    }

These should be the other way around. Screen of my network tab

Upvotes: 2

Views: 3433

Answers (1)

thanksd
thanksd

Reputation: 55664

When you dispatch an action, it doesn't have a then callback by default. That's only the case if the action returns a Promise. Your axios.get call should return a Promise, but you aren't returning it in your action. You should simply return it and then then callback will fire in your mounted hook.

loadApiCoins({ commit, dispatch, rootGetters }) {
  return Vue.axios({
    method: 'get',
    url: 'https://api.coinmarketcap.com/v1/ticker/',
    transformRequest: [(data, headers) => {
      delete headers.common.Authorization
      return data
    }]
  })
  .then(response => { commit('SET_API_COINS', response.data) })
  .catch(error => { console.log(error) })
},

Upvotes: 3

Related Questions