When the loading of data in vue is delayed, the information may not be accessible to various child components

`I recently started working with Vue and have encountered a problem. The main parent component on this page is as follows, with 2 child components. The structure is like this {CURRENT PAGE..} > {FancyButton} > {AnotherViewChild} I am trying to pass a value from the current parent component to the grandchild AnotherViewChild component using provide and inject. It works fine with the code below, but if I introduce a setTimeOut delay to retrieve the message, I end up with an empty [] value.

How can I resolve this issue? This usually happens when handling large data from the backend. The sample message data looks like this: message.value = [{id: 1, name: "ddl"},{id: 2, name: "Omen ser"},{id: 3, name: "natural sea"},...]

<script setup lang="ts">
import { ref, provide, computed, onMounted } from 'vue'
import FancyButton from './FancyButton.vue'
let someValue: any[]
  const message = ref<any[]>([])
  
  message.value = [
      {id: 1, name: "ddl"},
      {id: 2, name: "Omen ser"},
      {id: 3, name: "natural sea"},
      {id: 4, name: "Whale is swiming"},
      {id: 5, name: "Best food in"},
      {id: 6, name: "Better choice"},
      {id: 7, name: "What is next?"},
      {id: 8, name: "Other Option"},
    ]
  
  someValue = []
  onMounted(() => {
    setTimeout(() => {
    message.value = [
      {id: 1, name: "ddl"},
      {id: 2, name: "Omen ser"},
      {id: 3, name: "natural sea"},
      {id: 4, name: "Whale is swiming"},
      {id: 5, name: "Best food in"},
      {id: 6, name: "Better choice"},
      {id: 7, name: "What is next?"},
      {id: 8, name: "Other Option"},
    ]
  }, 2000)
  })
  
  
  console.log('-------->', message.value)
  provide('message', message.value)
  


computed(() => {
  console.log('-------->', someValue)
})


</script>

<template>
  <div style="border: 1px solid purple">
    <FancyButton>
       <AnotherViewChild />
      <div class="role">Role</div>
      <div class="role">Role</div>
    </FancyButton>
  </div>

</template>

<style scoped>
.role {
  color:green
}
.read-the-docs {
  color: #888;
}
</style>

When using setTimeout, I expect the data to be available in message.value after the specified timeframe and to be displayed in my child component <AnotherViewChild /> using provide and inject. Assistance would be appreciated.
Expected screenshot

Answer №1

To achieve the delay in data transfer between the parent component and the grand-child, you can follow these steps:

onMounted(() => {
  message.value = [
  {id: 1, name: "John Doe"},
  {id: 2, name: "Jane Smith"},
  {id: 3, name: "Michael Johnson"},
  {id: 4, name: "Sarah Brown"},
  {id: 5, name: "David Miller"},
  {id: 6, name: "Emily Davis"},
  {id: 7, name: "Chris Wilson"},
  {id: 8, name: "Laura White"},
];
  setTimeout(() => {
    provide('message', message.value)
   }, 2000);

});

By setting a timeout for assigning the value to message.value, you ensure that the provide() function is called after the assignment. This way, when the component mounts:

  1. provide() will be called with message.value = [];
  2. message.value will be assigned a value 2 seconds later, after provide() was called

Answer №2

Solved problems by moving the provide() function to the main file with 'message' provide('message', message) // removed .value

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 POST request encountering issue with success function not functioning as expected

I am currently working on implementing a basic HTTP post request to insert data into my database. The following pages are involved: register.php contains the registration form. maincons.js houses the application controllers. sqlregister.php include ...

Unexpected Behavior: using setTimeout in a ReactJS class component leads to incorrect value retrieval

App Component: class App extends React.Component { constructor() { super(); this.state = { user: 'Dan', }; } render() { return ( <React.Fragment> ...

Issue with Discord.js voice connection destruction函数

I've been attempting to implement a "Stop" command using the @discordjs/voice package, but I'm encountering an error. Despite my efforts to add some error handling, the issue persists. Below is the code snippet: async function stop(message) { t ...

CSS injection not working in Chrome extension content script

I'm attempting to add a CSS file to the PayPal homepage, but I'm encountering issues with it not working properly. Here is the manifest file I am using: { "manifest_version": 2, "name": "Paypal Addon", "version": "1.0", "descript ...

Generate a fresh FileReader instance using the downloaded file via XmlHTTPRequest

I am attempting to use an XmlHTTPRequest object (level 2) downloaded through a "GET" request in order to create a new FileReader object. My goal is to create the FileReader object within the onload function of the xhr. The file, which is a .gz file, downl ...

Learn how to instruct ajax to fetch the designated information and retrieve corresponding data from the database based on the selected criteria

Looking for some help with my 2 select boxes. The first box allows users to choose a brand, while the second box should display products from that brand fetched from the database. Unfortunately, I'm not familiar with AJAX and the script provided by a ...

Struggling with displaying a PDF file from the local directory in a NextJS application

I've been facing trouble importing and displaying my resume, a local file, within a react component. The code import myResume from '../assets/pdfs/myResume.pdf' is resulting in the error: Error: Cannot find module '../assets/pdfs/myRes ...

I am seeking a way to eliminate double quotation marks from a string without using the replace function

I need assistance in removing double quotes from the string "Hello". I have an array var ary = ['a', 'b' , 'c'] When I extract a value from the array, it returns the value in string format, such as ary[0] = "a", but I want i ...

Exploring the possibilities of combining AngularJS with a Bootstrap modal for a

Hello, I am currently attempting to update a modal select box using Angular and Bootstrap modals. Unfortunately, when I click the button, I am having trouble getting it to update the related select box value in the Bootstrap modal. I've tried differ ...

several javascript onclick event listeners for manipulating the DOM

I am currently experimenting with d3 and attempting to create a simple webpage to showcase my d3 examples for future reference. The page displays the output of the d3 code (specifically, the force layout from Mike Bostock) and then embeds the correspondin ...

What is the technique for incorporating FontAwesome icons onto an HTML 5 canvas?

I am encountering an issue while trying to use FontAwesome icons within my HTML 5 canvas. Here is what I have attempted: ct.fillStyle = "black"; ct.font = "20px Font Awesome"; ct.textAlign = "center"; var h = 'F1E2'; ct.fillText(String.fromCha ...

Execute AJAX request for two individual buttons

I have a scenario where I want to use two buttons to open separate PHP pages, but I would like to trigger both buttons with a single function. The AJAX function should then determine which button was clicked and open the corresponding PHP page - for exam ...

Learn how to implement pagination in AngularJS using the $http service

I need assistance in implementing pagination using Angularjs within the Ionic Framework. Can someone provide guidance on how to code pagination for fetching data from a JSON URL? controller.js angular.module('starter.controllers', []) .control ...

The information window is malfunctioning on Google Maps

I created buttons that are linked to specific locations on a map and they seem to be functioning, although not in the most efficient way. However, when attempting to add an info window to appear on the marker, it does not work as expected. I am unsure of ...

I am facing an issue with Angular 14 and Webpack 5, where certain unnecessary nodejs modules seem to be hindering me from successfully serving

I have recently started working on a cutting-edge Angular 14 application. My current node version is v14.20.0, and npm version is 8.17.0. Despite my best efforts, I seem to be facing an issue with multiple nodejs dependencies being included in my project ...

Is there a way to use the v-datetime-picker library to ensure that the end date is always after the start date?

I have implemented vuetify's v-datetime-picker component to store the start and end dates of an event. Here is my code: <template> <v-datetime-picker label="DateTime Start" okText="Accept" clearText="Cle ...

An unexpected 'u' token was encountered in the JSON data at the beginning while parsing with NextJS from the router.query

I have successfully passed data through the URL path from my main page to my quotes page component in NextJS 13. However, I encountered an error when trying to refresh the page. Quotes Page Component import React from 'react' import { useRouter ...

Using AngularJS, passing a value from outside a directive to the directive and detecting changes in the

As a newcomer to AngularJs, I am facing a challenge in retrieving data from outside a directive. The scenario involves multiple input fields being updated and the necessity for the directive to process this information. For instance, consider the code sni ...

Exploring MessageEmbed Properties

I am trying to retrieve the description of this Message embed. So far, I have used console.log(reaction.message.embeds) which displays the information below. However, when I attempt to access the description directly with console.log(reaction.message.embe ...

Changing the information of objects stored in arrays using React Three Fiber

My challenge is with an array of roundedBox geometry shapes called myShape. I am trying to figure out if it's possible to change the position of one of the shapes within the array without creating a new shape altogether. Ideally, I would like to updat ...