Get Off My Lawn
Get Off My Lawn

Reputation: 36341

Vue: axios executing synchronously instead of asynchronously on multiple components

I am trying to load ajax data when my component is created, however, this seems to make other items that also load via ajax within created() load synchronously instead of asynchronously when the following is executed, this ajax request takes about 2 seconds to run causing everything after to load in a synchronous style.

The following component takes about 2 seconds to load from the ajax call:

component1.vue

export default {
  data: () => {
    return { balance: { chips: 0, coins: 0, rewards: 0 } }
  },
  async created() {
    this.balance = (await axios.get('/api/player/balance')).data
  }
}

This component takes less then a second to load from the ajax call:

component2.vue

export default {
  data: () => {
    return { items: [] }
  },
  async created() {
    this.items = (await axios.get('/api/items')).data
  }
}

The two should load asyncronusly, however they do not, /api/player/balance runs, then /api/items runs.

I have also tried using .then() like this as well:

export default {
  data: () => {
    return { balance: { chips: 0, coins: 0, rewards: 0 } }
  },
  created() {
    axios.get('/api/player/balance').then(function (response) {
      this.balance = response.data
    })
  }
}

When I wrap this.balance = ... in a setTimeout, then the other items load fine.

Is there a better way to implement this so ajax request to run synchronously?

Edit

Using fetch solves the issue of request loading synchronously and allows them to load asynchronously.

export default {
  data: () => {
    return { balance: { chips: 0, coins: 0, rewards: 0 } }
  },
  async created() {
    let response = await fetch('/api/player/balance')
    this.balance = await response.json()
  }
}

Is there a way to do this with axios?

Upvotes: 0

Views: 6483

Answers (1)

Nafiul Islam
Nafiul Islam

Reputation: 1220

Have you tried without await? The await expression causes async function execution to pause until a Promise is fulfilled, that is causing your other items to hang until the ajax call is complete

EDIT

Can you try this with your other attempt?

axios.get('/api/player/balance').then((response) => {
  this.balance = response.data
});

The callback function you used in the then part uses ES5 notation where the keyword this will be scoped to that method only. moving into a ES6 notation will do. Or you can hold this into a new variable and work accordingly with that like this

const self = this;
axios.get('/api/player/balance').then(function(response) {
  self.balance = response.data
});

Although, the best practice (to me) is to update model in mounted() other than created()

Upvotes: 1

Related Questions