Vue.js: axios unexpectedly running synchronously across multiple components instead of asynchronously

Upon initializing my component, I am attempting to load ajax data. However, I have noticed that this causes other items loaded via ajax in the created() method to load synchronously rather than asynchronously. When this specific ajax request is triggered, it takes approximately 2 seconds to complete, resulting in everything else loading in a synchronous manner.

The first component, component1.vue, has a delay of about 2 seconds due to its ajax call:

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

In contrast, the second component, component2.vue, loads much quicker from the ajax call:

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

Despite efforts, these components are not loading asynchronously as expected. The /api/player/balance request is executed before the /api/items request.

I tried using .then() method as shown below:

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

However, nesting this.balance = ... within a setTimeout resolved the issue with other items loaded properly.

Is there an alternative approach to handle this and ensure asynchronous loading of ajax requests?

Edit

Using fetch successfully addressed the synchronous loading issue, enabling asynchronous loading of requests.

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()
  }
}

Can the same be achieved using axios?

Answer №1

Did you attempt the code without using await? The usage of await in an async function causes execution to pause until a Promise is fulfilled, which may be causing your other processes to hang while waiting for the ajax call to complete.

UPDATE

Have you considered trying this alternative approach?

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

The callback function written in ES5 notation within the then part restricts the scope of the keyword this to that specific method. You could switch to ES6 syntax or store this in a new variable and handle it accordingly as shown below:

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

However, I personally believe that updating the model in the mounted() method rather than in the created() method is a better practice.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a table using Ng-repeat in AngularJS: A Step-by-Step Guide

I'm trying to figure out how to create the table below using ng-repeat. Unfortunately, I don't have permission to modify the json structure so I need to work with it as is. Here's my json: $scope.carCollection = { 'Toyota': [ ...

When attempting to transfer data from an Ajax HTML form to a Flask template in Python upon clicking a button, encountered difficulties

I am a beginner with Flask and HTML. I need some help as I am struggling to retrieve parameter values from the HTML form (index1.html). Here is my HTML code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF ...

Encountering a TypeError in semantic-ui-react Menu: instance.render function not found

As a React novice, I have been working on a project that involves React for some time. However, I had not yet delved into dealing with packages and dependencies. It seems like my current issue is related to this. The problem emerged in a project where I w ...

I'm looking for the documentation for the latest version of Footable's Events. Can you point me

Does anyone know where to find information on the events that are fired for Footable and how to handle them? I checked the documentation at , but it doesn't provide much detail on events. If you have any resources or suggestions, please let me know! ...

Swapping values in JSON by comparing specific keys: A guide

I have JSON data that contains a key called reportData with an array of values: {"reportData":[ ["1185","R","4t","G","06","L","GT","04309","2546","2015","CF FE","01H1","20","23840","FF20"], ["1186","R","5t","R","01","L","TP","00110","1854","2016" ...

Learn the process of transmitting JSON data from a server-side (nodejs) to the client-side using Ajax

I have successfully set up a Node.js/express server to make a GET call to an API, which returns JSON data. Now, I am looking for ways to send this JSON data to my local JavaScript (client-server) in order to manipulate it by looping through and appending i ...

Encountered error: "Node.js and socket.io: Address already in use"

Experimenting with chat using Node.js and socket.io Currently, I am running Ubuntu 12.04 as a user and have a folder "pp" on my desktop. In this folder, I have placed a server file named server.js. Below is the client code: $(document).ready(function() ...

Warning: Update state in React-router-redux after redirection

I am currently developing an admin app for a project using react, redux, react-router, and react-router-redux. The version of react-router I am working with is v4.0.0, while react-router-redux is at v5.0.0-alpha.3 (installed with npm install react-router-r ...

In the realm of JavaScript, removing a DOM element can sometimes feel like an

For my project, I am using JavaScript, DOM, and AJAX to create pages. I am trying to figure out how to check if an element already exists and, if it does, remove it. This is what I have tried: var elementL = document.getElementById('divLogin'); ...

The sequence in which functions are executed when bound to an event in JavaScript

Recently, I found myself diving into the world of JavaScript to uncover details about how functions bound to a page event are executed. Take, for instance, when using an EventListener. Let's say you bind three functions - A(), B(), and C() - to the s ...

The Vue.js v-on:mouseover function is not functioning properly in displaying the menu

When I hover over a LI tag, I want to display a menu. I have successfully implemented it using a simple variable with the following code: @mouseover="hoverFormsControls=true" @mouseleave="hoverFormsControls=false" However, when I attempted to use an arr ...

Using NextJS to navigate user journey by mapping an array of values from Formik to

I really appreciate all the help I've received so far, but I'm facing an issue trying to map an object with an array within it to the router. Here is my current code: const initialValues = { region: query.region || 'all', campt ...

Programme for Server Login

After creating my own server, I attempted to implement a login feature to restrict access to its files. Unfortunately, using Javascript for this task proved to be insecure as usernames and passwords could easily be viewed in the source code: <form name ...

javascript detect when two div elements are overlapping

On my webpage, I have implemented the effect.shrink() function. However, when clicking quickly on the page, the div tags start overlapping with other elements. What is the best way to solve this issue? I am using both scriptaculous.js and prototype.js fo ...

Avoid data duplication or triplication by implementing a pop-up loop when adding new information

Seeking assistance in identifying the line of code that is causing data duplication or triplication when adding information in a pop-up form. The New/Update/Delete functions are functioning correctly, except for the Add function. The problem arises when i ...

Connecting an Express JS application to the GitHub API: A Step-by-Step Guide

Just recently, I delved into using expressJS for the first time and found myself struggling to connect it to the github API. My aim is to execute commands that can help me retrieve comments and other information from a specific repository. I would greatly ...

Experiencing a hiccup in React while attempting to play an mp3 file

My project includes the following code snippet, with an example mp3 file and npm package: https://www.npmjs.com/package/react-sound import React from 'react'; import Sound from 'react-sound'; class CustomSound extends React.Component ...

Is it possible to bring in all of the vue.js components from a directory?

Within my Nuxt project, I've organized my components in a folder called pages. Each page has its own folder within the pages directory with the same name as the page itself. For example, there is an index folder within the components/pages directory w ...

The Angular UI Datepicker is not reflecting changes in scope variables within the dates-disabled function

I'm currently working with AngularJS and the Angular UI Bootstrap. I've encountered an issue that I initially thought was related to scope, then initialization, but now I'm stuck trying to figure out what's causing the problem. I' ...

Solving Unique Data Types Directly in the Root of GraphQL

It seems like there's an obvious solution missing. I have IDs stored as [String] that I need to resolve to their corresponding full objects. Context This is the functionality I aim to achieve, but the crucial aspect missing is the resolvers: const ...