Unexpected Behavior Arises from Axios Get API Request

Below is a functional example in my CodePen showing what should be happening. Everything is working as intended with hard coded data.

CodePen: https://codepen.io/anon/pen/XxNORW?editors=0001

Hard coded data:

info:[
{
    "id": 1,
    "title": "Title one",
    "category_data": {
        "2": "Team",
        "7": "Queries"
    }
}
],

Issue:

However, when I replace the hard coded data with an AXIOS get call, the checkboxes in the CodePen do not work as expected. The All checkbox gets checked correctly, but the others do not.

I suspect that the slight delay in loading the API could be the reason for this behavior.

mounted() {
   this.getData(); 
},
methods: {
    getData: function() {
      axios
       .get('https://EXAMPLE.com/API/')
      .then(response => {
        this.info = response.data
        this.dataReady = true
      })
      .catch(error => {
        console.log(error)
       this.errored = true
  })
       .finally(() => this.loading = false)
    }
},

I ensure that the front-end is only rendered once the data is ready.

Is there a way to resolve this issue?

Thank you.

Answer №1

During the demonstration, using select() activates the "Select All" feature (checking all checkboxes), however, these checkboxes are not yet available until after getData() is completed. To resolve this issue, simply move the select() function to execute after getData():

async mounted() {
  await this.getData();
  this.select();
},
methods: {
  async getData() {
    const {data} = await axios.get(/* URL TO API DATA */);
    this.info = data;
  },
  // ...
}

See demo in action

Answer №2

When incorporating Axios into your Vue.js application, the use of the 'this' keyword within Axios can lead to confusion for the compiler in determining which object you are referring to - Axios or Vue. To address this issue, consider implementing the following code:

getData: function() {
   let app = this;
  axios
   .get('https://EXAMPLE.com/API/')
  .then(response => {
    app.info = response.data
    app.dataReady = true
  })
  .catch(error => {
    console.log(error)
   app.errored = true
  })
   .finally(() => app.loading = false)
  }

This approach should help resolve any confusion.

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

"Material-Table does not have the ability to insert a new row

Just started learning JS and React. I'm attempting to integrate Material-table with an add row button, but encountering issues where the added row is not reflecting. Every time I refresh the page, the rows are reset. I suspect there's a problem w ...

When executing a function, the previous React state continues to linger

Why is the updateUser() function only updating the last user instead of all users despite using useCallback and including users as a dependency? The expected output after clicking the update button should be: {"id":1,"name":"John& ...

Triggering transitionend event once with an added if condition

Currently, I have an application of an if statement that examines whether an element contains a style attribute. In the event that the style attribute is absent, it appends inline styling. Conversely, if the style attribute exists, it is removed. Furthermo ...

Issues with sending data through ajax using the post method persist on shared web hosting

I'm facing an issue with Ajax post data. It works fine on localhost but not on shared hosting. Here is my code: <script type="text/javascript> $(document).ready(function(){ $("#login").click(function(){ alert(& ...

Image Placement Based on Coordinates in a Graphic Display

Placing dots on a map one by one using CSS positions stored in arrays. var postop =[{'top':'23'},{'top':'84'},{'top':'54'},{'top':'76'},{'top':'103'}]; var ...

differences in opinion between JavaScript code and browser add-ons/extensions

As the owner and developer of an e-commerce website, I find that potential customers often contact us regarding ordering issues. Upon investigation, we consistently discover that the problem is caused by JavaScript errors. We frequently check their browse ...

I'm encountering an issue with automatically updating content on a webpage

I am currently working on a webpage that refreshes its content automatically to display the most up-to-date data from the database. Here's the JavaScript code I'm using: setInterval(function() { $("#status").load('refresh.php'); }, ...

What is the best way to manage communication with a database in a Node.js application?

I have a specific structure in my Express app: There is a db helper that I use to interact with my MariaDB database Here is the code snippet: var MariaSQL = require('mariasql'); var db = new MariaSQL(); var queries = { getUserByID : &a ...

Error encountered while making a REST API call in Ajax: Unforeseen SyntaxError: Colon unexpected

I am currently troubleshooting my code to interact with a REST API. My platform of choice is "EspoCRM" and I aim to utilize its API functionalities. The official documentation recommends using Basic Authentication in this format: "Authorization: Basic " ...

Customize the appearance of radio buttons in HTML by removing the bullets

Is there a way for a specific form component to function as radio buttons, with only one option selectable at a time, without displaying the actual radio bullets? I am looking for alternative presentation methods like highlighting the selected option or ...

Assign the output of a function to a variable

I am trying to retrieve data from a function call in nodejs and assign it to a variable. The desired output should be "Calling From Glasgow to Euston", but I'm currently getting "Calling From undefined to undefined". Here is the code snippet: functi ...

Employing a "cross-domain" approach to serve as a login gateway for a different domain

I need to configure the domain: aaaa.com so that it can host a login form for the website located at domain: cccc.com. It's important to note that I have complete control over the server at cccc.com and have successfully set up CORS on that server. A ...

Tips for adjusting the close date based on the selected date in a dropdown datepicker

Here is a sample code snippet: <input id="date1" name="start_date" id="dpd1"/> <select class="form_line_only form-control" name="ho_night"> <option selected> 0 </option> <option ...

Determining special characters within a string using VueJS

As a newcomer to VueJS, I am currently developing an application that requires a signup and login system. My goal is to inform the user if they have entered a special character such as /[&^$*_+~.()\'\"!\-:@]/. In order to achieve th ...

The error middleware in Express is not defined

I'm facing an issue where the Express API error messages are returning as undefined on the frontend. This is preventing me from displaying proper error messages to alert users. Interestingly, the error messages seem to appear fine in the developer to ...

The useNavigate() function seems to be failing to redirect to the '/protected' route

The issue lies in the redirection process after receiving the token from the API. Although the token is successfully saved in local memory, the redirect to the intended page does not occur as expected. Instead, a manual window refresh is required to naviga ...

VueJS fails to display table information

I am facing an issue with rendering data from my API using VueJS 2. Although the backend services are successfully sending the data, the HTML table does not display it. There are no errors shown in the debug console, and even the Vue Debug extension for Fi ...

Is there a way to determine if a table cell contains overflowing text compared to another cell?

Is there a way to detect if the content of the fourth td overflows from the second td? I am looking for a method to determine which td has overflowed text and identify which td's text is overflowing. What approach can be used to determine which td i ...

Adjusting the settimeout delay time during its execution

Is there a way to adjust the setTimeout delay time while it is already running? I tried using debounceTime() as an alternative, but I would like to modify the existing delay time instead of creating a new one. In the code snippet provided, the delay is se ...

Encountering the error message 'XMLHttpRequest is not defined' while incorporating getServerSideProps() in NextJS

I'm currently exploring NextJS with SSR and encountering an error when trying to fetch data from a Spotify playlist using the spotify-web-api-js library. This issue only occurs when executing on the server side: error - ReferenceError: XMLHttpRequest ...