Animation with Vue3 Suspense: From Parent to Child

I want to utilize Vue3 Suspense to trigger a loading state at the parent level that activates animations in the children. Once the request is completed at the parent level, I aim to remove the animation from the children.

App Header:

router-view(v-slot="{ Component, route }")
  template(v-if="Component")
    transition(:name="route.meta.transition" appear)
      KeepAlive
        Suspense
          component(:is="Component")
          template(#fallback='')
            div.loading-div LOADING !! 

Parent Template:

<template lang="pug">
section.discover-row
  div.discover-row-carousel
    DiscoverItem(
      v-for="(item, index) in DiscoverItemStore.automobiles"
      :key="item._id" 
      :item="item"
      :index="index"
    )
</template>

<script setup>
...
import { useDiscoverItemStore } from "@/stores/DiscoverItemStore"
const DiscoverItemStore = useDiscoverItemStore()
DiscoverItemStore.fetchItems()
</script>

Child Template:

Suspense
  template(#default='')
    div.item SHOW SOME STUFF
  template(#fallback='')
    div.loading-div CHILD LOADING !!

Request (from pinia store):

    async fetchItems() {
      this.automobiles = []
      this.items = []
      this.loading = true
      try {
        
        this.items = await fetch(discoverUrl)
          .then((response) => response.json()) 
        
        this.automobiles = [...this.items.Cars, ...this.items.Suvs, ...this.items.Trucks, ...this.items.Vans]
        this.loading = false
     ...

————————————————————

What's the best way to initiate the loading state at the parent level and display CHILD LOADING !! on each child instance until the request to fetchItems() at the parent level is completed?

Check out this codesandbox link for a demonstration of the issue (refer to the "home" tab).

Answer №1

The script setup tag now allows the use of await, which can be seen in more detail here: https://vuejs.org/guide/built-ins/suspense.html#async-setup

<script setup>
  import { useDiscoverItemStore } from "@/stores/DiscoverItemStore";
  const DiscoverItemStore = useDiscoverItemStore();
  await DiscoverItemStore.fetchItems();
</script>

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

Adding additional rows to an Array Object in JavaScript based on a certain condition

I am faced with a scenario where I have an array object structured as follows [ { id: 123, startdate: '2022-06-05', enddate: '2023-04-05' },{ id: 123, startdate: '2021-06-05', enddate: '2021-04-05' } ] The task at h ...

Struggling to display the retrieved data on the webpage

Code in pages/index.js import React from 'react'; import axios from 'axios'; import ListProducts from '@/components/products/ListProducts'; const getProducts = async () => { const data = await axios.get(`${process.env.AP ...

A guide to implementing toggle functionality on child elements

After clicking the button, the entire sidebar toggles, but I only want the side menus to toggle. Here is the relevant HTML code: <nav id="sidebar"> <div class="sidebar-header"> <img src="/fintantra/image ...

Stripe.js is frustrated by the duplicate inclusion in the code

Having an issue with Stripe.js - a warning keeps popping up in the console: Seems like Stripe.js has been loaded multiple times. Make sure to only load it once per page. Although the javascript is only present once on the page and the network tab in Dev ...

Storing data from multiple pages onto the final page using C# and ASP.Net - step-by-step guide!

I need assistance with saving an application that spans across multiple pages. Instead of saving after each step, I would like to review a summary of all the pages on the final page before saving the complete application. Can someone please guide me throug ...

Divide the array into distinct characters or verify the presence of a specific character

I have designed 3 buttons with unique names. When button A is clicked, it appends the value to an array. For example: <a href="#" class="answer" data-value="Football">Football</a> Clicking on this button will add "Football" to an empty array. ...

When onSucess is called within a Vue view, the metadata parameter returns undefined, whereas it works properly inside a

In my Vue component for Plaid Link, there is a function/action in my Vuex store called onSuccess. This function is supposed to call my backend API to exchange the public token for an access token and send some data about the link to the backend. However, I ...

The React application is unable to communicate with my Express application in a production environment, despite functioning properly during development

Currently, I am attempting to make a basic get request to my express backend located at mywebsite.com/test. The expected response from the server should be {"test": "test"}. While this is working perfectly fine in development on localho ...

Display a message to a user on the same HTML page using jQuery or JavaScript

How can I show a message to the user on the HTML page confirming their selected date without using an alert box? I attempted this code snippet, but I'm uncertain: document.writeln("The date you picked is: " + dateText); ...

Is there a method to preserve the received data after it has been retrieved?

I am currently utilizing EventBus for my project. Here is a snippet of my code: app.js window.EventBus = new Vue(); Here is the code for emitting events: EventBus.$emit('emitted', { SomeProperty: SomeData, }); And here is the code for re ...

Error: Trying to access "dishes" property on an undefined object gives a TypeError

Need Assistance Urgently! I have developed a web application using react and integrated it with node js. In the app, I am required to pass the status of a dish to the DishDetail Component indicating whether it is marked as "Favorite" or not. If a dish is ...

Is it possible to incorporate multiple versions of jQuery on a single web page?

Is it possible to use three different versions of jQuery on the same page? I am using codes from various tutorials that require different versions of jQuery: <script src="http://code.jquery.com/jquery-1.9.1.js"></script> <scri ...

When trying to access the "form" property of a form ElementRef, TypeScript throws an error

I've encountered an issue with accessing the validity of a form in my template: <form #heroForm="ngForm" (ngSubmit)="onSubmit()"> After adding it as a ViewChild in the controller: @ViewChild('heroForm') heroForm: ElementRef; Trying ...

HTML Elements for Displaying Undefined JSON Information

Hey there, I'm new to programming and I'm looking to display JSON data in an HTML table using jQuery. The issue I'm facing is that the output from the server shows up as 'undefined'. My goal is to have a constantly updated list of ...

(Applied jQuery) Trouble with div height in responsive layout

I have created jQuery full-page sliding panels that work perfectly on desktop devices. However, when the browser window is resized smaller, the panel divs fail to fill the page. If you want to view the issue in action, you can check out the JSFiddle demo ...

Updating a component with React JS setState() must be done on a mounted or mounting component

I encountered an issue where I am getting the error message setState(...): Can only update a mounted or mounting component., but I am struggling to find a solution. import React, { Component } from 'react'; import Loading1 from '../images/ ...

Obtain the number of elements rendered in a React parent component from a switch or route

I'm currently working on a component that is responsible for rendering wrapper elements around its children. One challenge I'm facing is determining which elements are actually being rendered as children. I've implemented functions to ignore ...

"Displaying Undefined Content when an Incorrect Value is Added, but functioning correctly with the right

I am attempting to populate the HTML table below with data from a JSON file: When I set var i = "0";, I receive undefined, but changing it to var i = "dv"; results in nothing being displayed. I am uncertain of the error I am making and what is causing th ...

What causes a "UnhandledPromiseRejectionWarning" while using Puppeteer?

What causes the following warnings to appear, and how can I resolve them? Warnings: (node:26771) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Protocol error (Runtime.callFunctionOn): Target closed. (node:26771) ...

Is it possible to implement Ajax functionality in JavaScript without using XMLhttp and connection the same socket for every request?

Can data on a page be communicated and updated without the need for reloading, all while avoiding the XMLHttpRequest object and using the same connection or socket for each request (without closing the connection each time)? ...