The Vue child component fails to render dynamic data upon initial page load

After examining the code below, I noticed that the alerts in my child component trigger before any of the code in the Parent's mounted function runs.

As a result, it seems like the child component has already completed initialization before the data is ready, causing it not to display the data until a reload occurs.

Although the data itself returns successfully from the API and is displayed as raw JSON inside the v-card in the layout.

My main concern is how can I ensure that the data requested in the Parent is ready BEFORE the child component is loaded? Most solutions I found focus on passing static data using props, but this approach fails when the data needs to be fetched first.

Within the mounted() function of the Parent, I have the following code to fetch the data:

const promisesArray = [this.loadPrivate(), this.loadPublic()]
await Promise.all(promisesArray).then(() => {
  console.log('DATA ...') // logs after the log in Notes component
  this.checkAttendanceForPreviousTwoWeeks().then(()=> {
    this.getCurrentParticipants().then((results) => {     
      this.currentP = results
      this.notesArr = this.notes // see getter below   
    })

The getter method that retrieves the data in the parent component:

get notes() {
  const newNotes = eventsModule.getNotes
  return newNotes
}

The rendering of the component in the parent template:

<v-card light elevation="">
  {{ notes }} // Raw JSON displays correctly here
  <Notes v-if="notes.length" :notesArr="notes"/>
</v-card>

The Child component:

...
@Prop({ type: Array, required: true })
  notesArr!: object[]

constructor()
{
  super();    
  alert(`Notes : ${this.notesArr}`) // no data here 
  this.getNotes(this.notesArr)    
}

async getNotes(eventNotes){
  alert(`Notes.getNotes CALL.. ${eventNotes}`) // eventNotes = undefined
  this.eventChanges = await eventNotes.map(note => {
    return {
      eventInfo: {
        name: note.name,
        group: note.groupNo || null,
        date: note.displayDate,
      },     
      note: note.noteToPresenter
    }
  })
}
...

As someone who is still learning Vue, I may be overlooking something simple. I have been trying to resolve this issue for a few days now without success, so any assistance would be greatly appreciated!

Answer №1

For newcomers to Vue, I highly recommend thoroughly going through the documentation along with familiarizing yourself with the tools in use - vue-class-component (an essential Vue plugin for declaring components as classes)

  1. Class Component Caveats - Opting for lifecycle hooks over using constructor

Instead of relying on constructor(), it's advised to transition the code to created() lifecycle hook

This adjustment should resolve the issues within your code in this specific scenario where the usage of the Notes component is dependent on v-if="notes.length" in the Parent component.

However, this approach may not suffice in all cases!

  1. The created() lifecycle hook (and data() function/hook) only executes once per component instantiation. The contained code serves as a form of one-time initialization. Therefore, if the parent component alters the content of the notesArr prop at some point in the future, the eventChanges won't reflect these modifications. This ties into Vue's performance optimization strategy of reusing existing component instances rather than recreating them when rendering lists with v-for or switching between components of the same type.

Many inexperienced users make this mistake, leading to questions like "why isn't my component reactive?" or "how can I trigger a re-render?" To address this issue effectively, it's crucial to design components as pure components (while applying the principles adapted from React). Computed properties play a vital role in achieving this in Vue.

Therefore, instead of introducing a separate data property like eventChanges (which may or may not be reactive), consider defining it as a computed property directly linked to the notesArr prop:

get eventChanges() {
   return this.notesArr.map(note => {
     return {
       eventInfo: {
         name: note.name,
         group: note.groupNo || null,
         date: note.displayDate,
       },     
       note: note.noteToPresenter
     }
   })
}

This adjustment ensures that whenever the parent updates the notesArr prop, the changes propagate to eventChanges, triggering a re-render of the component.

Additional Notes:

  • Avoid excessive use of async. If your getNotes function lacks asynchronous operations, remove it.
  • It's recommended not to mix async with then, as it can lead to confusion.

Choose either of the following approaches:

const promisesArray = [this.loadPrivate(),this.loadPublic()]
await Promise.all(promisesArray)
await this.checkAttendanceForPreviousTwoWeeks()
const results = await this.getCurrentParticipants()
this.currentP = results
this.notesArr = this.notes

or:

const promisesArray = [this.loadPrivate(),this.loadPublic()]
Promise.all(promisesArray)
  .then(() => this.checkAttendanceForPreviousTwoWeeks())
  .then(() => this.getCurrentParticipants())
  .then((results) => {     
    this.currentP = results
    this.notesArr = this.notes
  })

Refer to this resource for further learning opportunities.

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

Access the vue-router router-link component

I am working with a component that includes the following code: <router-link to="page"></router-link> <router-view></router-view> Within the Page component linked by the router, an event is triggered. The component containing the ...

When making an Ajax request to a webpage, you may receive both a success message and an

I attempted to initiate an ajax call to successtext.html located on my computer. However, upon checking my browser's console, I noticed that both success and error messages were displayed. Here is the script I used: <script type="text/javascript"& ...

"Prior to caching, angular-cache manipulates ng-resource's transformResponse function

Recently, I started utilizing angular-cache and stumbled upon this question on stack overflow. The user was inquiring whether the ngResource transformResponse function is executed before caching. It turns out that it isn't. However, is there a workar ...

Obtain module-specific members through programmatic means

When working on a browser, the code may appear like this: //retrieve all enumerable properties of `this` function globalMems() { var g = this; var ret = {}; for (var prop in g) { ret[prop] = g[prop]; } return ret; } In Node.js, this does ...

unable to display router offspring

My router is named '/shop' and has a child route called /list/:id for the component listproduct. However, when I try to render the link as mylocalhost/shop/list/0812018381, it doesn't render correctly. Here are my routes: { path: &apo ...

Instead of leaving an Enum value as undefined, using a NONE value provides a more explicit

I've noticed this pattern in code a few times and it's got me thinking. When you check for undefined in a typescript enum, it can lead to unexpected behavior like the example below. enum DoSomething { VALUE1, VALUE2, VALUE3, } f ...

Create your masterpiece on a rotated canvas

My goal is to draw on a canvas using the mouse, even after rotating and scaling the canvas container. The issue I am facing is that the mouse coordinates get affected by the rotation and scaling, making it difficult to draw correctly. I have tried switch ...

Importing Jquery into the head of a Yii2 page

I am working on my Yii2 application and have a script that requires jQuery to be loaded in the header of the page. I am aware that there is a parameter that can be configured within AppAssets.php : public $jsOptions = [ 'position' => &bs ...

How to design a React Native view that spans across two rows

I am looking to design five similar views using react native. Please refer to the image for reference. The layout consists of four smaller views on the right side and one large view on the left side. ...

Determine whether the current time exceeds a certain time of day

While this may have been asked before, I am struggling to find an answer. How can I determine if the current time is after 17:30 each day? In my scenario, I need to check if it is past 17:30 on Monday to Friday, and if it is Saturday, I need to check if i ...

Tips for implementing multiple selectors in YUI

Is there a way to use multiple selectors in YUI (YUI 2) similar to jQuery? $('h1, h2, el1, el2, .content, .title').css('color', 'red'); How can I achieve the same in YUI without having to individually add classes using YAHOO ...

What's the best way to manage endless routing options in express.js?

After reviewing the topic of handling routes in Express.js on Stack Overflow, I came across the following example : var express = require("express"); var app = express(); app.get("/", function(request, response) { response.send(&quo ...

The split function in JavaScript is exhibiting some unusual behavior

There is something wrong with my code challenge1 = () => { var data = fs.readFileSync('santa21.txt', 'utf8'); data = data.toString(); dataSplit = data.split(' ') console.log(dataSplit); }; challenge1(); The result of the ...

a guide on incorporating jQuery ajax requests with node.js

Although I came across a similar question on Stream data with Node.js, I felt the answers provided were not sufficient. My goal is to transfer data between a webpage and a node.js server using a jQuery ajax call (get, load, getJSON). When I try to do this ...

"Is there a way to modify the color of the button once it's been clicked, but only for the specific button that was

Looking to create a Quiz App using React and facing an issue where all buttons change color when clicked, instead of just the one that was clicked. Any solutions on how to make only the clicked button change its color in React.js? App.js import Main from ...

Retrieving information from a child component within the view

Currently, I am utilizing Laravel 5.2 along with Elixir 5 and also Vue 2.0. I find myself in a dilemma on how to access and import data from a component in the view element using features like v-if. Let me outline my current setup: resources\views& ...

Seeking assistance with Shopify - Enhancing User Experience with Javascript Cookies

Is there a way to adjust the settings of how long Shopify stores cookies on your computer for? Currently, it retains cart information for two weeks. Any suggestions on how to modify this? I am considering two possibilities: 1) Making shopping members-only ...

Interactive rotating display with constantly updating information

Recently I started learning angularJS and I must say, I am already hooked. I have developed a website that pulls data from JSON files (created by external scripts) locally to show real-time information on various pages. Now, I want to include a sliding car ...

JavaScript (geolocation) error: Unhandled TypeError - Invocation not allowed

Encountering the Javascript error "Uncaught TypeError: Illegal invocation" while executing the code var nativeGeoloation = window.navigator.geolocation.getCurrentPosition; nativeGeoloation(function (){ alert("ok")}); Despite attempting to call the code w ...

Having trouble receiving a response from axios

My goal is to use axios to submit a blog post and display a response message. If the response is "success," the process should proceed. For testing purposes, I am only using console.log("success ok"). However, I encountered a puzzling issue that I cannot f ...