Is there a different technique I can use to display an axios response within a v-if statement? Any other methods I should

As a newcomer to Vue.js, I'm struggling with certain concepts even after extensively reading the documentation!

My goal is to show a glyphicon when my API call returns true.

However, since the call is within a for loop iterating over multiple items, I'm unable to store the response in a variable due to it getting overwritten with each iteration...

The specific code where I want to implement this display is as follows:

<div class="list-group-item"
          v-for="item in exercices['data']" :key="item">
          <h3 class="list-group-item-heading titre">
            <p><a > {{ item[1] }}</a>
                <span v-if="checkIsValid(item[0]) === true">
                  <span class="glyphicon glyphicon-ok" ></span>
                </span>
            </p>

And the axios call is made in this part of the code:

      checkIsValid(id, index){
        this.$axios
      .get('http://127.0.0.1:5000/checkIsValid/'+id+'/'+ Vue.prototype.$userMail)
      .then(response => ( ??? )
      )
      }

Any suggestions or ideas on how to approach this challenge would be greatly appreciated!

Thank you in advance!

Answer №1

If your method checkIsValid makes an asynchronous call, using it directly in a v-if is not possible. To handle this, you can iterate through each element in the exercices array in the mounted hook and update their validity status.

export default {
    // ...
    data() {
        return {
            exercices: [
                {
                    // ...
                },
                {
                    // ...
                }
            ]
        }
    },
    mounted() {
        this.exercices.forEach(element => {
            this.$axios.get("URL_HERE")
                .then(() => {
                    this.$set(element, "isValid", true);
                })
                .catch(() => {
                    this.$set(element, "isValid", false);
                })
        });
    }
}

Make sure to use this.$set for proper reactivity. For more information on change detection caveats, refer to this link.

Update your v-if condition to:

<span v-if="item.isValid">

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

Find the location in a node.js script where a promise was rejected

Recently, I encountered a code snippet from an npm package that has been causing me some trouble. The issue is that I'm having difficulty in pinpointing where the rejected promise is being created or rejected within node.js. const someHiddenEvil = fu ...

Strange actions observed in JavaScript addition operations

In my Angular application, I have the following TypeScript function: countTotal() { this.total = this.num1 + this.num2 } The value of num1 is 110.84 and the value of num2 is 5.54. I determined these values by watching this.num1 and this.num2 in the C ...

What are the ways to utilize vue-i18n setup within and beyond Vue components when working with Quasar?

Hello, fellow developers. I am currently working on implementing internationalization in Quasar, using Vue 3 (Composition API) and vue-i18n. My goal is to make internationalization available throughout the entire application, not just within Vue components ...

What sets apart optionalDependencies from peerDependencies in the Meta optional?

Why are both marking dependency as optional and what is the specific use-case of each? Is peerDependenciesMeta intended for npm packages while optionalDependencies is meant for projects? For example, in my npm package, certain modules require dependency ...

Updating a nested object in MongoDB using Mongoose and calling the markModified method

Regrettably, I am lacking a suitable record to carry out a test on this. Furthermore, I have been unable to locate any information related to this particular issue. Let's consider a scenario where I have a document structured as shown below: { ema ...

What is the best way to include an external JavaScript file in a Bootstrap project?

I am brand new to front-end development and I'm attempting to create an onClick() function for an element. However, it seems like the js file where the function is located is not being imported properly. I've tried following some instructions to ...

When starting a new project with Angular 7, the option to set up routing is automatically included without asking for confirmation

After switching from Angular 6 to version 7, I encountered an issue while creating a new project in CLI using ng new [app-name]. It simply starts without giving me the option to include routing or styling in my project. Just a heads up, I am currently run ...

Steps to display a variable in JavaScript on an HTML textarea

I'm working on a JavaScript variable called 'signature' var signature; //(Data is here) document.write(signature) Within my HTML document, I have the following: <div id="siggen"> <textarea id="content" cols="80" rows="10">& ...

The mismatch between JSON schema validation for patternProperties and properties causes confusion

Here is the JSON schema I am working with: { "title": "JSON Schema for magazine subscription", "type": "object", "properties": { "lab": { "type": "string" } }, "patternProperties": { "[A-Za-z][A-Za-z_]*[A-Za-z]": { "type" ...

Troubleshooting problems with dynamic elements and qTip

On my page, I have an UpdatePanel where new forms are added when clicked. These new elements contain images that need to utilize qTip. This is the current setup: $(document).ready(function () { $('.ttip').qtip({ conten ...

Calculating the mean value of a multidimensional array that has been sorted in JavaScript

Check out the structure of my JSON File below. { "questions": ["Question1", "Question2"], "orgs": ["Org1", "Org2", "Org3"], "dates": ["Q1", "Q2", "Q3"], "values": [ [ [5, 88, 18], [50, 83, 10], ...

Determine whether the current page was reached by pressing the back button

Can we determine if the current page was loaded via a back button press? Here is the scenario: index.html (contains a link to page1 in the menu) page1.html (loads content from ajax with a link to page2) page2.html (user presses the BACK button) page1.h ...

the function does not wait for the DOM content to finish loading

As I execute the code, an error occurs stating that setting innerText of Null is not allowed. I understand that this is because my function runs before the DOM is completely loaded, but I am unsure of how to resolve this issue. Attempts have been made usi ...

Rotating the camera in first person perspective using Three.js

After struggling to find updated help on first player rotation in three.js, I am facing a challenge where most of the solutions provided are using functions that no longer exist in the current library version. I am attempting to implement a feature where ...

Is it possible for the outcome of a component to be passed to render and actually show up as undefined

I am currently working on creating a wrapper component for an API call in order to display "loading" if the API hasn't updated yet. As I am new to React, I am struggling with passing the state to the ApiResp component: After checking the console.log ...

Issue with Electron-vue: 'compute:' not functioning as expected

My attempt to create a simple example using the element-ui library was not successful. There are two 'switches' with different active state values: 2 and 1. The values of the switches are supposed to be displayed in <p>{{sw1}}</p> and ...

Utilizing JSON and CodeIgniter within HTML elements

I am interested in creating a private chatroom using CodeIgniter and JSON format. I want the JSON data retrieved to be displayed in a list structure like <ul><li>messageinJSON</li></ul>. This formatting will allow me to customize th ...

Require assistance in accessing the second tab on a webpage using JavaScript tabs

Currently, I have a web page with two tabs that are initially hidden until the corresponding tab button is clicked. The click event is managed by jQuery. For example, let's assume that tab 1 is the default one when the page loads. Now, I am looking fo ...

Updating specific data in MongoDB arrays: A step-by-step guide

{ "_id":{"$oid":"5f5287db8c4dbe22383eca58"}, "__v":0, "createdAt":{"$date":"2020-09-12T11:35:45.965Z"}, "data":["Buy RAM","Money buys freedom"], & ...

Tips for dynamically passing parameters to functions in JavaScript?

Looking for a solution to dynamically receive input from the user in my function: divResize = { myDiv:function(width, height) {...} } divResize.myDiv(100,400); I want to make these numbers interactive and changeable based on user input. How can I achie ...