Search code examples
javascriptvue.jsaxiosvuex

What's the best way to have API calls happen at different times?


In my Vue application My API calls timeout when I call them at the same time. I'm using axios and my data is going to a VueX store.

I've put my API calls in setTimeout methods and set them at different times to fire. It works but it seems messy and not the best way to write code. Is there a way to achieve the same effect with out the setTimeout, maybe async/await?

This is in my main component. These are called on a button click.

            this.$store.dispatch('undoButton', this.undoBtnAPI)
          setTimeout(() =>{
            this.$store.dispatch('getSQLData', this.apiQuery)
          }, 500)
        }, 300) 

Here's the API call in the VueX store

actions: {
getSQLData (context, query) {
      console.log(query + 'query var')
      return new Promise(function (resolve, reject) {
        console.log('SQL Action Called')
        console.log('query var: ' + query)
        axios.get(MS_SQL_URL + '/api/' + query)
        .then(response => {
          this.commit('initialDataUpdate', response.data.recordset)
          // console.log(response.data.map(item => item.ProcessSequence))
        })
        .then(response => {
          this.commit('completeDataLoading')
        })
        .catch(e => {
          console.log('SQL API error: ' + e)
          this.mssql.push(e)
        })
      }.bind(this))
},
undoButton (context, query) {
      return new Promise(function (resolve, reject) {
        axios.get(MS_SQL_URL + '/api/' + query)
        .then(response => {
          this.commit('initialUndoButtonData', response.data.recordset[0]['CSN'])
        })
        .then(response => {
          this.commit('completeUndoDataLoading')
        })
        .catch(e => {
          console.log(`SQL ERROR ${e}`)
          this.mssql.push(e)
        })
      }.bind(this))
    }
}

Solution

  • You can just chain them with then and they will run one after another:

       this.$store.dispatch('undoButton', this.undoBtnAPI).then(()=>{
           this.$store.dispatch('getSQLData', this.apiQuery)
       })