Vue Component Update DisorderI hope this meets your expectations

Below is my code using Bootstrap, Vue, and Axios:

SETUP:

*Please disregard the tab-contents in component_a

main.js

Vue.component('component_a', {
  props: ['info'],
  template:   `<div> 
    // Component A template code here
}

Vue.component('component_b', {
  data: () => {
    return {
      columns: null
    }
  },
  props: ['info'],  
  template: `<div>
    // Component B template code here
}

var app = new Vue({
  el: '#app',
  data () {
    return {
      info: [],
      activeDisplay: "dashboard",
    }
  },
  methods: {
    // Methods for getting API data and setting active display
  },
  mounted () {
    this.getData
  }
})

main.html

  <div v-if="activeDisplay === 'ep'">
    <component_b @set-active-display="setActiveDisplay" :info="info"></component_b>
  </div>
  <div v-else-if="activeDisplay === 'dashboard'">
    <dashboard></dashboard>
  </div>
  <div v-else-if="activeDisplay === 'activeEp'">
    <component_a :info="info"></component_a>
  </div>
  <div v-else>
    <dashboard></dashboard>
  </div>

PROBLEM:

Description of the issue you are facing with updating the root instance object after an interaction with Component B.

Order of Operations:

Flow breakdown of how the events are processed by Vue and Axios to troubleshoot the issue.

EDIT1:

More insights into the debugging process and discovering the timing issue between Axios call completion and data update in Vue.

Final thoughts on needing to wait for Axios call to complete before displaying the data and seeking guidance on how to achieve this within Vue.

Answer №1

It seems that I will need to wait for the response from the Axios call before displaying the required data. The question now is how to achieve this in Vue?

To ensure that you wait for the completion of the axios.get() call within the getApiData() method before updating this.activeDisplay, you should first return the result of the axios.get() call (which is a Promise). This allows callers to use await.

getAPIData(id,type) {
  // BEFORE:
  //axios.get(...)

  // AFTER:
  return axios.get(...)
}

Next, modify the setActiveDisplay() method to be an async function so that you can await the result of getApiData():

// BEFORE:
//setActiveDisplay: function (id, ad) { 

// AFTER:
async setActiveDisplay(id, ad) {
  if (...) {
    await this.getApiData(...)
  }
  this.activeDisplay = ad
}

Alternatively, you can avoid using async/await and utilize Promise.prototype.then():

setActiveDisplay: function (id, ad) {
  if (...) {
    this.getApiData(...).then(() => this.activeDisplay = ad)
  }
}

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

Tips on resolving the flickering issue in dark mode background color on NextJS sites

One problem I am facing is that Next.js does not have access to the client-side localStorage, resulting in HTML being rendered with or without the "dark" class by default. This leads to a scenario where upon page reload, the <html> element momentari ...

Comparing npm install --save versus npm install --save-dev

Hey everyone, I've been using npm install -g to globally install node modules/packages, but I'm a bit confused about the --save and --save-dev options. I tried looking it up on Google, but I'm still not entirely sure. Can you guys help clar ...

When transitioning an iOS Swift app to the background, a NodeJS error arises: 'Headers cannot be set after they have been sent to the client'

My app is built using Swift/SwiftUI. I utilize the ObservableObject and JSONDecoder to retrieve data from my Node.JS Express API and display it within the app: struct DevicesList: Decodable { var data: [DeviceInfo] } struct DeviceInfo: Decodable { ...

Under specific circumstances, it is not possible to reset a property in vue.js

In Vue.js, I have developed a 'mini-game' that allows players to 'fight'. After someone 'dies', the game declares the winner and prompts if you want to play again. However, I am facing an issue where resetting the health of bo ...

If the Request does not recognize the OAuth key, generate a fresh new key

I am working with a React Native Frontend and an Express.js backend. The backend makes calls to a 3rd party API, which requires providing an OAuth key for the user that expires every 2 hours. Occasionally, when calling the API, I receive a 400 error indi ...

Looking to display a div with both a plus and minus icon? Having trouble getting a div to show with left margin? Need assistance hiding or showing div text

Can someone please review this source code? Here is the demo link: http://jsfiddle.net/bala2024/nvR2S/40/ $('.expand').click(function(){ $(this).stop().animate({ width:'73%', height:'130px' }); $( ...

Issue encountered while using AJAX to load images

Currently, I am utilizing a jQuery plugin to fetch images from Flickr. My aim is to organize these images into 3 columns dynamically as they are loaded, ensuring that each image is placed in the shortest column to achieve close to equal lengths for all col ...

Mismatch in SSL version or cipher for ExpressJS

I am encountering an issue with https in express and I am struggling to comprehend it: Here is the code snippet from my previous project (which functions correctly): index.js: var fs = require('fs'); var http = require('http'); var ...

What is the best way to dynamically identify the property names of my object?

let weekData = []; for (let i = 0; i < 7; i++) { const weekdayName = moment().subtract('days', i).format('dddd'); weekData.push({ [weekdayName]: 0 }); } I'm trying to create a list of objects with dynamic pr ...

"Exploring the power of Vue.js through dynamic and recursive components

I am struggling with creating a recursive custom component that calls itself. Unfortunately, I keep encountering an error. An unknown custom element: <TestRec> - have you registered the component correctly? For recursive components, ensure to specif ...

Can you explain the functionality of this Angular JS code snippet?

How is it possible that the following code snippet works in Angular JS? var app = angular.module('store',[]); (function(){ app.controller('StoreController',function(){ this.blabla = student; }); })(); var student = ...

mysterious supplier factoryprovider <- factory <- angular js controller

I'm encountering an issue with injecting dependencies from a service to a controller. Despite adding it, I keep receiving the following error: Unknown provider: websiteFactoryProvider <- websiteFactory <- listCtrl My main goal is to display ...

Incorporating local JSON data into HTML: A Step-by-Step

I'm completely new to javascript and the utilization of json. What I want to accomplish is quite straightforward, although I am encountering difficulties. My objective is to create a website consisting of two pages: one that showcases artists and ano ...

Tips for successfully passing ExpressJS locals variable to an EJS template and utilizing it as a parameter when invoking a JavaScript function during the onload HTML event

const hostname = "192.168.8.154"; const port = 3002; app.use('*', function (req, res, next) { db.collection('sys_params').find().toArray() .then(sysParams => { //console.log(sysParams); app.locals.sysParams ...

Developing and integrating views within a node-webkit desktop application

For my file copier desktop application built with node webkit, I aim to create a seamless flow where the initial check for existing profile data determines the first page displayed. The header with static links/buttons to various views remains consistent ...

Color-Thief Node plugin reported an issue: "The provided image has not finished loading."

While working in Node/Express, I attempted to utilize the npm package color-thief to extract the dominant color from an image. Unfortunately, it failed with the error message stating that the "image given has not completed loading". The intriguing part is ...

Exploring the creation of a dynamic graph with d3.js

I'm new to d3 and attempting to create a graph layout. var w = 1000; var h = 500; var dataset = { nodes: [{ name: 'Alice' }, { name: 'David' ...

The function image.getState is not recognized (when trying to implement ol in an Angular project)

I attempted to integrate the code provided in an angular(4) application at the following link: However, I encountered an error every time I tried to launch the browser. To start with, here are my imports (both libraries were locally installed via npm): ...

Error: selenium web driver java cannot locate tinyMCE

driver.switchTo().frame("tinymce_iframe"); String script="var editor=tinyMCE.get('tinymce_textarea');"; JavascriptExecutor js=(JavascriptExecutor) driver; js.executeScript(script); I'm encountering a WebDriverException while try ...

Exploring ways to create fresh arrays derived from the original array

On our company website, we have a wide array of vehicles available for purchase. Among these vehicles, there is a specific group of vans with detailed information such as the model and value. {vanNumber: "7654628", vanDescription: "VW Campervan", value: { ...