Using conditional rendering to compare the outcome of an asynchronous function within v-if condition

I have a Vue component for a sidebar with the following template:

Vue.component('navigation',{
  template:`
    <ul class="nav">
      <li v-if="checkIfUserIsAdmin() == true" id="adminMenu"></li>
      <li id="userMenu"></li>
  `,
  methods: {
    checkIfUserIsAdmin() {
      var result = false;
      axiosInstance.get("/Profile/GetUserInfo").then(userInfo => {
        result = userInfo.data.u.isAdmin;
      })
      .catch(userError => {
        swal({
          title: "Operational Platform",
          text: "Unable to retrieve user info"
        });
        result = false;
      });
      return result;
    }
  }
});

Some code has been omitted for brevity.
When I make a request to /Profile/GetUserInfo, I receive a JSON response that includes true for the isAdmin value, but the adminMenu element is not being displayed. I suspect that the issue lies within the v-if condition. I even attempted changing the condition to

v-if="checkIfUserIsAdmin() == 'true'"
, but this did not resolve the problem.

Answer №1

To obtain the desired outcome, you must be patient for the method's response.

Initially, execute the checkIfUserIsAdmin method upon mounting the component. Within the checkIfUserIsAdmin method, ensure to save the query result in the adminMenuDisplay variable, which will then be monitored using v-if.

Vue.component('navigation',{
  template:`
    <ul class="nav">
      <li v-if="adminMenuDisplay" id="adminMenu"></li>
      <li id="userMenu"></li>
  `,
  data() {
    return {
      adminMenuDisplay: false
    };
  }
  methods: {
    checkIfUserIsAdmin() {
      var result = false;
      axiosInstance.get("/Profile/GetUserInfo").then(userInfo => {
        this.adminMenuDisplay = userInfo.data.u.isAdmin;
      })
      .catch(userError => {
        swal({
          title: "Operational Platform",
          text: "Unable to retrieve user info"
        });
        this.adminMenuDisplay = false;
      });
    }
  },
  mounted() {
    this.checkIfUserIsAdmin();
  }
});

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

Error: The function $(...)button is not recognized

I encountered the error Uncaught TypeError: $(...).button is not a function when trying to add a product. I have checked and confirmed that the button is visible on the root, but the error persists. This issue only occurs on one specific page in Opencart ...

I'm having an issue where the Bootstrap dropdown submenu is not displaying properly depending on

I'm facing an issue creating a dropdown menu and submenu using Bootstrap on Vue 3 and bootstrap 5.2 Here is the JSON menu data: [ { "id": 1, "name": "Menu 1", "active": 1, &q ...

What could be causing the Error 400 message to appear when trying to upload a JSON file via an HTTP request?

This Code Snippet is Essential function makeRequest() { var dataToSend = { "username": "234zu", "subject": "qwertz", "content": "qw", "created_at": "2018-12-15 22:18:54", "updated_at": "2018-12-15 22:18:54" ...

Having difficulty capturing an error related to an invalid form body in discord.js

I built a command to send an embed based on JSON data, and it's working well for the most part. When I input the data correctly, the bot sends it to the channel as expected. However, if someone tries to insert text in a link section, it crashes the b ...

Solving the Angular form glitch: error message not displaying

I am facing an issue with my simple form where I am not able to display errors related to the fields. <html lang="en" ng-app="MyApp"> <head></head> <body ng-controller="AppCtrl"> <form name="myForm" id="myForm"& ...

The issue of invalid prop in Vue Utils

Having an issue with Vue Util Error: console.error [Vue warn]: Invalid prop: type check failed for prop "icon". Expected Object, Array, String, got Undefined In my parent component 'myComp', there is a global component Font Awesome n ...

Update picture using Vanilla Javascript for mobile display

I am looking to change my logo color to white when viewed on mobile devices. Currently, I have the following code for changing the logo on scroll using vanilla JavaScript. The code toggles between a dark and light logo based on the scroll position. Howev ...

Trouble presenting information retrieved from API

I'm encountering an issue with displaying the data I fetched from an API. I'm not sure what's causing the problem... I attempted to use the map() function to access the data, but it's not functioning as expected either. import React fr ...

Provide JWT token back to JavaScript Single Page Application after completing OAuth login

Currently, I am building a single-page application (SPA) using Vue.js, which will eventually become a Cordova application. Additionally, I am developing a backend API with Lumen. I am working on implementing login functionality with Facebook and Google. T ...

Exploring the functionalities of ng-value and ng-model in text input form fields

As I create a form to update information in a database, everything seems to be functioning properly. The selected data is being retrieved correctly; however, it is not displaying in the text inputs on the webpage. Although the information appears correct ...

How to selectively filter an array of objects using another array in JavaScript

Imagine you have an array filled with objects: people = [ {id: "1", name: "abc", gender: "m", age:"15" }, {id: "2", name: "a", gender: "m", age:"25" }, {id: "3 ...

Utilizing JSON and AJAX to mine data from databases

I've been working on creating a basic "search" box using Javascript, AJAX, PHP, and JSON. I'm focusing on the "world" database that I downloaded from the MySQL website for this particular project. I've hit a roadblock when trying to retrieve ...

Removing HTML DOM elements from a string using JavaScript: A step-by-step guide

Hey there, I'm currently working on my angular application. When it comes to inserting the first 100 characters of content into the "description" meta tag for Facebook sharing, I've run into an issue. The description ends up including the HTML el ...

The Typewriter Effect does not appear alongside the heading

For my portfolio website, I am using React to create a unique typewriter effect showcasing some of my hobbies. Currently, the code is set up like this: "I like to" [hobbies] However, I want it to display like this: "I like to" [h ...

Strategies for managing the integration of mixins, filters, and directives in a sprawling Vue.js project

Hey there! I am currently working on a large Vue app and I've stumbled upon a challenge. Can someone please guide me on how to effectively organize the importing of mixins, filters, and directives? I seem to be struggling with this concept and would g ...

Adding a click function to a div individually when they share the same class in HTML

My goal is to include 4 unique divs inside a timeline container: This is how I envision the structure: <div id="timeline" > <div class="timeline-bar t-1"></div> <div class="timeline-bar t-2"> ...

What is the best way to showcase 100 json data entries within an HTML document?

Starting from scratch with html, css, and javascript, I've embarked on a basic learning project. Within this project, I plan to create two main pages: a list page and a detail page. The list page will showcase posts on the html screen, featuring only ...

Error in Angular 4: Undefined property 'replace' causing trouble

I've been trying to use the .replace() JavaScript function in Angular 4 to remove certain characters from a string. Here is the code snippet from my component: @Component({...}) export class SomeComponent implements OnInit { routerUrl: string = &apo ...

"An error occurred when processing the JSON data, despite the JSON

Incorporating Ajax syntax for datatables and angularjs has been my current endeavor. Encountering an invalid JSON response with the following: self.dtOptions = DTOptionsBuilder.fromSource([{ "id": 860, "firstName": "Superman", "lastName": "Yoda" }]) How ...

Why is my Vue/MySQL Database not showing up online, even though it is accessible locally?

While my application runs smoothly locally, I encounter an issue when deploying to the Heroku server. The page contents linked to the MySQL Database fail to display without any CORS errors or fetch call issues in Chrome Dev Tools. The page loads, but remai ...