Home > Net >  Problem with async await in vue component
Problem with async await in vue component

Time:07-08

I have strange situation, and I can't understand why in different location function works not the same. I would like to retrieve data by axios. When I input my dispatch for axios in mounted hook - it works correct and I can write data from axios to draftData. But, if I wrap my dispatch in function and locate in methods - data don't write in draftData. Why it so? I wrote what was required of me (async/await).

Example.vue

<script>
import LineChart from "../LineChart";
export default {
  components: { LineChart },
   data: () => ({
    loaded: false,
    chartData: null,
    labels:[],
    datasets:[],
    draftData:null,
  }),
  methods: {
    loadIncomings(){
      this.loaded = false
      try {
        let clubId = '5c3c5e12ba86198828baa4a7'
        let dateFrom = '2021-06-01T00:00:00'
        let dateTo = '2022-07-02T23:59:59'
        let groupBy = 'month'
        this.$store.dispatch('loadIncomings', {clubId, dateFrom, dateTo, groupBy})
        console.log('loadIncomings---', this.$store.state.incomings)
        this.draftData = this.$store.state.incomings
        console.log('draftData---', this.draftData)
        this.loaded = true
      } catch (e) {
        console.error(e)
      }
    },
    calcIncomings() {
      if (this.loaded){
        for (let el of this.draftData ) {
          console.log(el)
        }
      }
    }
  },
  async mounted () {
    await this.loadIncomings(),
    await this.calcIncomings()

  },
}
</script>

It looks like so:

enter image description here

"---UpdateIncomingsInfo---" - it is console.log from mutations (vuex). This work after axios.

CodePudding user response:

Your loadIncomings function isn't async, so it doesn't return a Promise nor wait for your dispatch to be over.

Try like this:

async loadIncomings(){
  this.loaded = false
  let clubId = '5c3c5e12ba86198828baa4a7'
  let dateFrom = '2021-06-01T00:00:00'
  let dateTo = '2022-07-02T23:59:59'
  let groupBy = 'month'
  try {
    await this.$store.dispatch('loadIncomings', {clubId, dateFrom, dateTo, groupBy})
    this.draftData = this.$store.state.incomings
  } catch (e) {
    console.error(e)
  } finally {
    this.loaded = true
  }
},

You can even return the data from your action directly (in addition to set the store from mutation):

this.draftData = await this.$store.dispatch('loadIncomings', {clubId, dateFrom, dateTo, groupBy})
  • Related