Pass data that has been asynchronously resolved from the parent component to the child component using props in Vue

Main component:

<template>
  <div>
    <Nav :data="data" />
  </div>
</template>

<script lang="ts">
// ... imports removed for clarity
@Component({
  components: {
    Nav: () => import('@/components/Nav.vue')
  }
})
export default class Home extends Vue {
  public nav: NavInterface = {}

  private getData(): Promise<any> {
    // ... this.$http - using axios instance
    return this.$http
      .getData()
      .then((resp: any) => {
        this.data = resp.data.nav
      })
  }
}
</script>

Sub-component:

<template>
  <div class="nav">
    <ul>
      <li v-for="(nav, index) in data">{{ nav.id }}</li>
    </ul>
  </div>
</template>

<script lang="ts">
// ... imports removed for brevity
export default class Nav extends Vue {
  @Prop({ default: null }) public readonly data!: NavInterface

  private mounted(): void {
    console.log(this.data) // Returns undefined because promise is not resolved yet
  }
}
</script>

A challenge arises when the promise resolves in the parent component before propagating to the child one. Is there a way to only load the child component after successful resolution of the getData() promise since the child component relies on the parent's data?

One approach could involve utilizing a watcher in the child component but it feels like a workaround:

@Watch('data')
private onPropChange(val: any) {
  console.log(val) // Correct data becomes available
}

I would rather conditionally render my child component only after the promise has been fulfilled.

Answer №1

Below is an illustrative example of an approach you can take, but remember to customize it according to your specific needs:

<template>
  <div>
    <Nav v-if="isVisible" :items="navItems" />
  </div>
</template>
export default {
  data() {
    return { navItems: [] };
  },
  computed: {
    isVisible() {
      return this.navItems.length > 0;
    },
  },
  mounted() {
    return this.$http.getData().then(resp => {
      this.data.navItems = resp;
    });
  },
};

Important: In the code snippet above, I am using the length of the navItems array to determine visibility. Depending on your requirements, consider creating a separate variable (e.g. isLoaded) to control rendering of the Nav component in scenarios with no items or errors.

Answer №2

To enhance your parent component, consider incorporating an if statement:

<template>
  <div>
    <Nav v-if="loaded" :data="data" />
  </div>
</template>

Within the function:

return this.$http
      .getData()
      .then((resp: any) => {
        this.data = resp.data.nav
        this.loaded = true
      })

Alternatively, if data.nav is null or does not exist after populating the data

    <template>
      <div>
        <Nav v-if="data.nav" :data="data" />
      </div>
    </template>

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

AngularJS $http.get request not working as expected

Hi there, I'm currently facing an issue with retrieving data from a webpage for use on my own website. I'm working with AngularJS and attempting to fetch data from . When checking my page in Chrome, I encountered the following error: Refere ...

Click the button to access the provided link

I need to add a link for redirection to some buttons. Here is an example of the button code: <Tooltip title="Open New Ticket"> <IconButton aria-label="filter list"> <AddTwoToneIcon /> </IconButton> </T ...

A guide to effortlessly converting Any[] to CustomType for seamless IntelliSense access to Properties within Angular/Typescript

Our Angular service interacts with the backend to retrieve data and display it on the UI. export interface UserDataResponse { id: number; userName: string; } AngularService_Method1() { return this.http.get<UserDataResponse[]>(this.appUrl + "/Ap ...

Consumer using ActiveMQ-Stomp is not receiving any messages

I attempted to create a JavaScript code for an ActiveMQ subscriber that would subscribe to a specific topic, but unfortunately I am not receiving any messages after establishing the connection. The topic that needs to be subscribed to is COO.2552270450083 ...

Input field for postal code containing only numbers (maximum 5 digits) in Angular version 4/5

I am struggling with creating an input field that accepts numbers. If I use type="text", I can only type 5 characters of alphanumeric data, but if I use type="number", it allows any number input without limiting it to just 5 numbers. Thank you in advance f ...

Tips on displaying a particular JSON attribute?

After starting with a JSON string, attempting to convert it into a JSON object and then trying to print a specific field (such as firstName), I am getting undefined. What could be the issue here? Thank you for your help! var string = '{"firstName ...

Delete entries in table based on user-provided criteria

Hello there, I'm new to this community and seeking some assistance. I am currently learning jQuery/Javascript and have encountered a problem that has me stumped. The issue arises with a table where rows are generated based on a user-selected number f ...

Tips for stopping execution in Discord.js if the user no longer exists?

I'm currently working on a discord bot and encountered a minor issue. I am using "messageReactionRemove" and "messageReactionAdd" to manage certain roles by removing or adding them, but the problem arises when a user leaves the server. When this happe ...

Can you provide guidance on utilizing the Login Event within the Electron Framework?

I need some assistance in understanding the functionality of the Event: 'login' feature within the Electron Framework. Is this similar to the Password Autofill/Remember Password feature typically found in web browsers? I'm interested in util ...

Tips on attaching a class to elements in a loop when a click event occurs

In my HTML, I am displaying information boxes from an array of objects that are selectable. To achieve this, I bind a class on the click event. However, since I am retrieving the elements through a v-for loop, when I select one box, the class gets bound to ...

The Bootstrap nav-link class functions perfectly in Firefox, smoothly guiding users to the appropriate section. However, it seems to be experiencing some issues

I am currently working on customizing a one-page web template and I don't have much experience with Bootstrap. The template can be found at . My issue is that the menu items are not functional in Chrome. When I click on any menu item, nothing happens ...

ESLint detected a promise being returned in a function argument where a void return type was expected

I'm encountering a recurring error whenever I run my ESLint script on multiple routers in my server. The specific error message is as follows: error Promise returned in function argument where a void return was expected @typescript-eslint/no-misuse ...

Effortless method of organizing information like scores

I have developed a multiplayer game that will be played on a server, and I need to save the high scores of the players. These stored scores should be consistently available and easily accessible for all players at any time. Can anyone suggest a good appro ...

Effectively controlling two distinct Azure resources within one domain name through domain routing

I am currently in the process of deploying a React application on Microsoft Azure that includes a basic content management feature. Essentially, when users visit the website and access static content, the app retrieves HTML code from a database and display ...

Send JSON information to a Spring Boot server application

I am brand new to working with Spring Boot. Currently, I am attempting to send registration form data (in JSON format) from a Vue frontend to a Spring Boot backend. However, the backend always indicates that the received data is null. How can I properly re ...

Select specific columns from an array using Typescript

I have a collection of objects and I'm looking for a way to empower the user to choose which attributes they want to import into the database. Is there a method to map and generate a separate array containing only the selected properties for insertion ...

Having difficulty executing the .exec() method of the nodejs simple-ssh module

I am currently using npm's simple-ssh library to establish a connection with a remote host as the root user. I have an additional superuser account named serviceUser. My objective is to switch to this user by running su serviceUser (Note: su service ...

What role does NPM play in the deployment of a Node.js App with AWS Beanstalk?

I'm interested in the workflow of an AWS Beanstalk deployment, particularly regarding the installation of packages. I assume that npm is used during the process to install packages on the server(s). However, I am curious to know if AWS Beanstalk utili ...

Troubleshooting the problem of divs overlapping when scrolling in JavaScript

I am experiencing some issues with full screen divs that overlay each other on scroll and a background image. When scrolling back to the top in Chrome, the background shifts down slightly, and in Safari, the same issue occurs when scrolling down. I have cr ...

Tips for incorporating Javascript in an innerHTML inline css situation

I'm just starting to learn about html5 and php. I'm curious about how to incorporate javascript into my existing code. Currently, I have data from a database displayed in an HTML table. My goal is to align the output of the last cell more toward ...