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

Updating the object in router.get and res.render in Node.js and Express after loading

When loading the page, I encounter an error with req.body.firstname.length inside router.use. The error states: TypeError: Cannot read property 'length' of undefined The issue arises because the default value is undefined for the input form. ...

Modify the contents of an array within a string using JavaScript

let message = "hello https://ggogle.com parul https://yahoo.com and http://web.com"; let url = ["https://ggogle.com", "https://yahoo.com", "http://web.com"]; I'm trying to replace all URLs in the 'message' array with "***" from the 'ur ...

Obtaining a button from a dialog in Google Apps

It seems like I'm overlooking something really simple here, but I'm struggling to enable an interface button from a dialog box in Google Apps. When I try setting the disabled attribute to false in a this object under the "click" function, the bu ...

Error: Unable to access the 'prototype' property of an undefined object (inherits_browser.js)

After updating our app to a newer version of create-react-app, we started encountering the following error: This error seems to be related to inherits_browser.js, which is likely from an npm module that we are unable to identify. The line in error within ...

What steps can I take to ensure that the v-main element occupies at least 70% of the viewport height in Vuetify?

As a newcomer to Vuetify, I am still learning the ropes. One thing I've noticed is that <v-main> automatically expands to fill the space between <v-app-bar> and <v-footer>, taking up the entire viewport height. My concern arises wh ...

Pause the ajax response using jQuery

I encountered a simple issue that is causing me trouble. It seems that when I send an ajax request, there isn't enough time to assign the value to the combonews variable: jQuery.ajax({ type: "POST", url: "People.aspx/LoadCombo ...

JavaScript quiz featuring randomized questions with selectable radio buttons

I need assistance in creating a feature on my webpage where users can select the number of questions they want to answer (ranging from 1 to 10). The selected number of questions should then be displayed randomly, without any duplicates. I am not very famil ...

Unable to save cookies on mobile browsers, but functioning properly on desktop computers

Currently, I am facing an issue with my ExpressJS app hosted on Heroku and a frontend React app hosted on Netlify. The problem arises when a user logs in successfully and is directed to the home page showing personalized content. Upon landing on the home p ...

JavaScript's Selenium WebDriver - Explicit Waiting

Currently, I am utilizing selenium-webdriverjs. My objective is to pause until a specific element is displayed. To accomplish this, I have implemented an explicit wait that operates effectively: var shown = false; driver.wait(function(){ driver.findEl ...

Implementing Event Listeners in Vue 3.0: A Guide to Attaching to the Parent Element

How can I attach an addEventListener to the parent element in Vue 3.x? I discovered that you can access the parent by using this code: import { getCurrentInstance, onMounted } from 'vue' onMounted(() => { console.log(getCurrentInstance() ...

Guide to utilizing the importcss plugin in TinyMCE Version 4.0.10: Troubleshooting content_css loading issue and resolving style dropdown display problem

We are currently using the latest version of TinyMCE, specifically v 4.0.10 Our goal is to load content_css and have a dropdown of styles available in the styleselect menu. According to TinyMCE 4.x documentation, we attempted to achieve this by incorpora ...

How can I preserve the file extension of an ejs file as .html?

I'm in the process of building an expressjs application using the ejs template engine. However, I'd like to retain the file extension as .html instead of using .ejs. The main reason for this is that I am using Visual Studio for my development wor ...

How can I extract the text within an element based on the position of the

In my current project, I have incorporated the incredibly useful jQuery TextRange plugin. Within a highlight div positioned above a textarea element, it is crucial for me to identify the specific element that the user is currently editing. To better illust ...

Creating an 8-bit grayscale JPEG image using HTML5 and encoding it from a canvas source

Is there a simple method to convert an 8-bit grayscale JPEG from Canvas using client side technologies in a web browser (such as HTML5, canvas, WebGL, and JavaScript)? Are there any pre-made JavaScript libraries available for use, without requiring extens ...

Utilizing NextJS to retrieve cookie data within React components

Currently, I am working with a Next.js frontend and an Express backend. For authentication, I am utilizing cookies and have set up protected routes using Next.js middleware. The next step in my project involves accessing the cookie response within React ...

"Update data on a webpage using Javascript without the need to refresh the

I encountered a problem with my code for posting messages in the "chatbox". When I include return false; at the end of the function, the data is not submitted. However, if I remove it, the data submits successfully. JavaScript Code function dopost() { ...

The AJAX request is failing to reach the server

I'm currently using AJAX to populate a dropdown, but for some reason the call isn't reaching the server. Upon checking Firebug, I see the following error: POST 0 status 404 not found This is the code I'm working with: function selec ...

Running the `npm run build` command excludes the `.cache` folder from the `

Currently, while working on a Vue Application, I have encountered an issue. When I run the command npm run build to generate the dist folder, a new folder named '.cache' is automatically created within node_modules. This folder contains files wit ...

Steps for making a cookie in Node.js using Socket.IO

I'm currently exploring the process of creating a cookie while utilizing socket.io. Although I have successfully figured out how to read cookies, I am struggling to find resources on how to actually create one. socket.on('test', async funct ...

What exactly does the context parameter represent in the createEmbeddedView() method in Angular?

I am curious about the role of the context parameter in the createEmbeddedView() method within Angular. The official Angular documentation does not provide clear information on this aspect. For instance, I came across a piece of code where the developer i ...