Issue with child component mounted before parent component creation

I have encountered an issue in my Vue application. It seems that the child component's mounted function is being executed before the parent component's created function.

I am passing props from the parent component to the child component and I want to use these props in the child component's mounted function. However, the props are not available in mounted because they are set after created in the parent component. Can someone help me resolve this problem so that the child component can properly set this.userCopy to the prop received as this.user?

Parent Component

<template>
 <div>
  <Info :user="user" />
 </div>
</template>
<script>
 import Info from 'views/info';
 export default {
  components: {
    Info
  },
  data () {
    return {
      user: {
        first_name: '',
        last_name: '',
      },
      errors:[]
    }
  },
  created() {
    this.fetchUsers();
  },
  methods: {
   fetchUsers() {
      this.$axios.get('/user.json')
      .then(response => {
          this.user = response.data;
      }).catch(error => {
        this.errors = error.response.data.error;
      });
    },
  }
 }
 </script>

Child Component

<template>
 <div>
  {{userCopy}}
 </div>
</template>
<script>
 export default {
  props: ['user'],
  data () {
    return {
      userCopy: {}
    }
  },
  mounted: function() {
   var that = this;
   this.userCopy = this.user
  }
 }
</script>

Answer №1

When the user is updated asynchronously after the component has already been mounted, the user will initially be undefined in the mounted() hook.

Solution 1: The parent component could choose to conditionally render the child component based on the existence of user, ensuring that the user prop of the component has a value upon mounting:

<Info v-if="user" :user="user">
export default {
  data() {
    return {
      user: null, // asynchronously updated in fetchUsers()
    }
  }
}

Solution 2: The child component could utilize a watcher on the user property to update a separate userCopy:

export default {
  //...
  watch: {
    user(user) {
      this.userCopy = { ...user } // perform a shallow copy
    }
  }
}

It is important to note the use of the spread operator to create a shallow copy of the user object.

Answer №2

One approach I've taken is to use a loaded variable in my data. Subsequently, on the child component that depends on this data, I implement a v-if="loaded" directive.

data() {
  return {
    loaded: false
  }
},
async created() {
  try {
    await this.fetchUsers();
    // The loaded variable will be updated once the users have been fetched.
    this.loaded = true;
  }
  catch(error) {
    console.error('Failed to fetch users', error)
  }
}

Then, in your template, simply include...

<child-component v-if="loaded" />

Answer №3

In fact, the initialized function is called before your child component's loaded. The issue lies in the fact that the retrieveData method is asynchronous (a Promise) and requires to be awaited.

async initialized() {
    await this.retrieveData();
  },

Experiment with this code, waiting for the async task to complete.

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

Using Javascript to extract a custom attribute from a button element

In my HTML, there is a button that has a custom property called data-filter-params: <button class="button" type="submit" data-filter-params="{'Type', 'Filter.Type'},{'Code','Filter.Code'}" >Filter</button&g ...

Having trouble loading the URL into an iframe using angularJS

With AngularJS, I am attempting to dynamically load the URL address "myLink" into an iframe in another HTML file. The data.No variable is obtained from elsewhere and functions correctly (providing the necessary ID for the URL). In the controller - "Transa ...

Restricting Checkbox Choices with JavaScript by Leveraging the forEach Function

I am developing a checklist application that limits the user to selecting a maximum of three checkboxes. I have implemented a function to prevent users from checking more than three boxes, but it is not working as expected. The function detects when an ite ...

Is it possible to dynamically load a specific div when the page loads, relying on the

I am using JQuery SlideUp and slideDown methods to toggle the visibility of panels. How can I load or display the first record's contact information as a default? Currently, it loads blank because I set the panel's display property to none: < ...

Avoiding the backslash in JavaScript

<script type="text/javascript"> console.log(#Fileurl#); jQuery.ajax({ url: "http://xyz:8800/aaa/bbb/ccc", type:'POST', dataType: 'JSON', data:{"file":"#Fileurl#"}, success: function ...

Issue with React conditional display not functioning properly post user input into a form

Thank you in advance for your help. I am working on a component that displays a button based on the const results. However, I noticed that when I insert "Balaton," the button only appears after I add another character to the string. So the string becomes ...

Using method as a filter in AngularJS: A guide to implementing custom filters

I've created a custom data type called Message: function Message(body, author, date) { this.body = body; this.author = author; this.date = date; this.stars = []; } Message.prototype.hasStars = function() { return this.stars.lengt ...

"Phraseapp is in the process of refreshing the primary language document

I currently have a locale file that contains various text keys that need to be translated. Each key corresponds to a specific text that needs to be translated into different languages: { key1: "Text to translate", key2: "Another text to translate", ...

Identifying sluggish GPU performance on a mobile device using three.js: A guide for developers

My game runs extremely slow on older mobile devices like the Samsung Galaxy S4 and iPhone 5 when shadows are enabled. However, when shadows are turned off, performance improves significantly. Is there a way to detect a slow GPU in order to disable sh ...

Ways to alter the typography style if the text exceeds a certain length

I need some assistance with using Material UI in my ReactJs project with TypeScript. I am trying to decrease the font size of typography when the text exceeds 3 lines. Here is a snippet of my code: const checkFontSize =() => { if(text.leng ...

Count the number of times an iteration occurs in AngularJS/JavaScript

I need assistance with my code snippet below, as I am trying to determine the count of all instances where $scope.rm is equal to "failed" or when $scope.percentage is less than 50. angular.forEach(result1, function (value, key) { $scope.percentage ...

Exploring the features of Vue.js: A guide to implementing a dropdown menu in

As a newbie to Vue, I am exploring the usage of dropdown menu element in my project. <el-dropdown trigger="click"> <span class="el-dropdown-link"> <i class="el-icon-more" /> </span> ...

Attempts to access the URL but receives no feedback

While using casperjs, I encountered an issue with scraping a particular link - . It seems like I am not receiving any response from this link. No matter what I try, it always stops at this point in the cycle. I have isolated the problem, but I just can&apo ...

Tips for retrieving specific values from drop-down menus that have been incorporated into a dynamically-sized HTML table

How can I retrieve individual values from dropdown menus in HTML? These values are stored in a table of unspecified size and I want to calculate the total price of the selected drinks. Additionally, I need the code to be able to compute the price of any ne ...

Guide to writing a unit test for a parameter decorator in NestJs

I want to implement a unit test for a basic custom decorator that I created, but I'm facing some challenges. This decorator was developed based on the solution provided here. I have Keycloak authentication set up and using this solution in my controll ...

Issue with fetching API data and sending it to the Node server

My node backend is all set up and running smoothly for GET requests, but I'm facing an issue with POST requests as the data doesn't seem to be getting sent to the backend. Here's the code snippet: fetch("http://localhost:3000/", ...

Vue v-model not consistently updating

Question: In certain cases, the v-model that binds a string to an input field may not update as expected. Scenario: I am integrating Vue into a Laravel application where the main component includes two nested components: <template> <div> ...

Tips on capturing the response data in UI testing automation

Currently, I am working on automating a login page using WebDriverIO for UI Automation. After clicking the Login button, a request to *.com/user/login is triggered in the background. I need to capture this call's response in order to obtain a token r ...

Successive pressing actions

I am struggling to grasp a unique Javascript event scenario. To see an example of this, please visit http://jsfiddle.net/UFL7X/ Upon clicking the yellow box for the first time, I expected only the first click event handler to be called and turn the large ...

Update the document by sending the data and making changes based on the AJAX response

Currently, I am avoiding using jQuery and trying to work with the following code in PHP: <?php header ( 'Content-Type: text/xml; charset=utf-8' ); $con = @mysql_connect ( "localhost", "root", "" ) or die ( "Couldn't connect to database" ...