In a Vue Application, the static HTML elements are loaded before fetching data

Utilizing VueJS and VueRouter in my application has presented a challenge. The issue lies in the fact that static HTML elements within the Vue Component load before the data is fetched, resulting in empty forms and tables being displayed initially. I have implemented the fetch method within the created() lifecycle hook, however, this approach seems to be causing confusion for me. Below is an excerpt of my code:

<template>
  <div id="app">
    <h1>My Data length: {{fetchedData.length}}</h1>
    <li v-for="value in fetchedData">{{value}}</li>
  </div>
</template>


export default {
  name: "MyVueComponent",
  data() {
    return {
      fetchedData: [],
    }
  },
  methods: {
    async getData() {
       await fetch('https://cli-vue-application.herokuapp.com/user/getUser', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
      })
          .then(function (response) {
            return response.json();
          }).then(function (data) {
            this.fetchedData= data
          }.bind(this));
    }
  },
  created() {
    this.getData();
  }
}

The fetched data is correct, however, the h1 element displaying a length of "0" initially for a few seconds indicates that the fetch occurs after the static HTML is rendered.

Answer №1

To display the content only if there is data fetched, you can use a simple if statement with fetchedData:

<template>
   <div id="app">
     <div v-if="fetchedData.length">
      <h1>My Data length: {{fetchedData.length}}</h1>
      <li v-for="value in fetchedData">{{value}}</li>
     </div>
   </div>
</template>

If you want to provide a loading message or spinner while waiting for the data to arrive, you can also include an else block:

<template>
   <div id="app">
     <div v-if="fetchedData.length">
      <h1>My Data length: {{fetchedData.length}}</h1>
      <li v-for="value in fetchedData">{{value}}</li>
     </div>
     <div v-else>
       Loading...
       //Or insert your chosen spinner component here
     </div>
   </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

How to align the navbar toggle button and list items to the right in Bootstrap 5

I'm struggling with a simple html page that has a fixed navbar at the top. Everything looks great when viewed in full-screen mode, with centered links. However, when the page size is reduced, it collapses to a toggle button on the left side. What I re ...

AngularJS: Hide Row in NG-Grid Based on Condition

I am a beginner in angularJS and I have a requirement to hide a row in my ng-grid table if the value of a column is '0'. The grid consists of 4 columns: User Today This Week This Month I need to hide an entire row if the value in the 'Th ...

What is the appropriate time to end a connection in MongoDB?

Utilizing Node.js Express and MongoDB for my API, I encountered an issue with the mongoClient connection. The data fetching process worked smoothly at first, but without refreshing it threw an error stating "Topology is closed." const express=require("e ...

Guide to utilizing an if statement to return a string as the title in a Tooltip pro

When attempting to dynamically set the title of a tooltip based on a function and using an if statement, I encountered an error. const getStatusMessage = (answer: AnswerStatus) => { if (answer == AnswerStatus.ANSWER_SUBMITTED || answer == AnswerStatus ...

Using Vuetify to display text fields in a single row

Check out this Vue component template (View it on CODEPEN): <div class="some-class"> <v-form > <v-container @click="someMethod()"> <v-row> <v-col cols="3" sm="3" v-for="p in placeholders" ...

What's the issue with my ExpressJS req.query not functioning as expected?

My NodeJS repl setup includes an input, button, and h1 element. The goal is to update the HTML inside the h1 element with the value of the input upon button click. Here's a glimpse of my code: index.js: const Database = require("@replit/database ...

Text box size in user input not adapting on mobile devices

Website: Visit the Cutter Travel Calculator here I've encountered an issue with my user input text boxes on mobile. Despite setting their width using the formidable forms plugin, the size adjustment doesn't seem to apply when viewed on mobile de ...

"There seems to be an issue with the KeyListener function in

The error I'm encountering is: index.html:12 Uncaught TypeError: Cannot read property 'addEventListener' of null I'm unsure about what went wrong. The intention behind the code was to store the result of the selected radio button into a ...

The text color in Vuetify 3 remains the same even after changing the background color

I'm having trouble setting both the background color bg-color and text color text-white for a simple button. It seems that once I set the background color, there is no way to change the text color without creating a new class and using !important. < ...

Using AngularJS to handle click events and blur events

I am attempting to dynamically change the class based on user interaction in my code. The class should switch between "large" and "active" depending on whether the input field is filled or not. Please see the modified script below. <div class="snippe ...

Having trouble getting two different filters to work properly when filtering data in AngularJs

I have created a plunkr to demonstrate my current situation: The user is required to type a word into the textbox, and upon clicking the button, an angular service retrieves data from a DB based on the input text. The retrieved data is then displayed in a ...

fa icons moving the elements aside

I'm attempting to design a navigation menu with tabs, but I'm facing an issue where the tabs containing "fa icons" are consuming too much space, causing other elements to be shifted to the right or below (if there were more lines). How can I pre ...

Is it possible to view newly added text in real-time on a separate client in Node.js without relying on socket.io?

I am in the process of creating a straightforward web application where users can input phrases. The app works fine, except for one issue - it doesn't display new additions from other users instantly. I am aware that socket.io could solve this problem ...

Attempting to determine income in JavaScript with the inclusion of two distinct rates

Trying to come up with a salary calculation for different rates within the same timeframe is proving to be quite challenging. For instance, between 10:00-15:00 the rate is $20 per hour and from 15:00 onwards it drops to $15 per hour. Check out the entire ...

Is it appropriate for a search service to provide a 404 response?

In the world of web development, let's say I have a server-side search feature that is triggered by JavaScript (AJAX). What happens if I search for something like "chewy dragees", and although the server successfully receives the search request, it do ...

Uploading a file to a URL using Node.js

Looking for a way to replicate the functionality of wget --post-file=foo.xpi http://localhost:8888/ in nodejs, while ensuring it's compatible across different platforms. In need of assistance to find a simple method for posting a zip file to a specif ...

Tips for analyzing a JSON response from a meme API using HTML and JavaScript

I'm looking to integrate an API into my website in order to fetch random memes from reddit. The API was developed by D3vd and can be found on github at When I make a request to (the api), the response typically looks like this: { "postLink ...

Transferring variables from the $(document).ready(function(){}) to the $(window).load(function(){} allows for seamless and

Just think about if I successfully create percent_pass at the time of document.ready, how can I transfer that variable to window.load? $(document).ready(function() { jQuery(function() { var ques_count = $('.question-body').length; va ...

Having trouble deleting JavaScript object properties within a loop?

Struggling to comprehend the behavior of this particular piece of javascript code. const devices = searchResult.results.forEach(device => { const temp = Object.keys(device.fields); for(var property in temp) { if(device.fields.hasOwnPro ...

Get a collection of images packed into a single zip file

My current function downloads multiple images and saves them to a user's "download" folder, although it only works in Chrome. I am looking to enhance this function by combining the downloaded images into a single zip file. Below is my existing code. ...