Defer the rendering of Vue.js pages until the data request is completed

I am currently working on a page that retrieves data from the server using axios.

My goal is to wait for the axios request to complete before rendering the page content.

The reason behind this approach is that I already have a prerendered version of the page. While the axios request is in progress, I prefer to display the prerendered data instead of leaving the screen blank (to avoid CLS issues).

This is my current implementation:

export default {

  ....

  created() {
    this.fetchData().then((returnedData) => this.personData = returnedData);
  },

  data() {
    return {
      personData: {
        name: "",
      },
    };
  },

  methods: {
    async fetchData() {
      const response = await axios.get("api/persondata/");
      return await response.data;
    },
  },

  ...

}

Essentially, I am looking for a way to turn the axios request into a "synchronous" operation or find a method to make the created() function wait until the request is completed.

An ideal scenario would involve preventing the rendering process altogether and displaying the prerendered page if the axios request fails.

Do you have any suggestions on how to achieve this?

Answer №1

To ensure that the data is loaded before displaying it, you can use a v-if statement rather than v-show. This will prevent any errors from occurring when attempting to access values in your response object that may not exist yet.

<template>
  <div v-if="!isLoading">
    Show your updated data here
  </div>
  <div v-else>
    Show your pre-rendered data here
  </div>
</template>
export default {

  data() {
    return {
      personData: {
        name: "",
      },
      isLoading: true
    };
  },

  methods: {
    async fetchData() {
      const response = await axios.get("api/persondata/");
      return await response.data;
    },
  },
  async mounted(){
     this.personData = await this.fetchData()
     this.isLoading = false
  }
}

It's recommended to wrap your code in try/catch blocks to handle any potential errors that may arise.

Based on my experience working on large Vue projects, using this method along with components for rendering and formatting data tends to be more effective than relying solely on the router. While router hooks are suitable for smaller applications, they can become less manageable when additional features like page access tools or global routing functionality are needed.

A common pattern involves: View -> reading ID parameter -> passing it to a component for data rendering -> component fetching data via axios based on ID. Even if the route parameter changes (without changing the route itself), your component will still update accordingly with the parameter change.

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

In MUI v5 React, the scroll bar vanishes from view when the drawer is open

Currently, I am working on developing a responsive drawer in React using mui v5. In the set-up, the minimum width of the drawer is defined as 600px when it expands to full width. However, an issue arises when the screen exceeds 600px - at this point, the d ...

Troubleshooting issue with Next.JS Redux dispatch functionality inside getStaticProps() not functioning as

I have recently started working with Next.JS and decided to integrate Redux into my Next.JS application. I'm facing an issue where my page is supposed to display a list of posts fetched from an API. Everything works fine when I use useEffect() to disp ...

Converting a string to regular text in JavaScript (specifically in ReactJS)

When I fetch data from an API, sometimes there are special characters involved. For example, the object returned may look like this: { question : "In which year did the British television series &quot;The Bill&quot; end?" } If I save t ...

Mapping URLs to objects in JavaScript, TypeScript, and Angular4

I have implemented a class called SearchFilter class SearchFilter { constructor(bucket: string, pin: number, qty: number, category: string) { } } When the user performs a search, I populate the filter i ...

Having trouble configuring individual route files in Express JS

I'm having trouble separating my login route from the default app.js and route/index.js files. When I try to access localhost:3000/login, I keep getting a 404 Not Found error. I've searched on StackOverflow for similar questions and tried follow ...

Activate ajax search in select2 by hand

I recently integrated the select2 plugin with jQuery into my website. For the most part, it functions perfectly. One particular feature I have is a search widget that utilizes select2 and remote data search. When I enter a search query using a keyboard ...

Using Vue.js to create numerous modal popups

Currently, I am using Vue.JS for a research project at my workplace. My focus right now is mainly on the front-end. I have a table with several entries, and when a row is clicked, I want a modal popup window to display further details about that specific ...

Protractor's Get Attribute Value function may return null after updating the Chrome version

Having trouble with Get Attribute Value returning null after updating to the latest Chrome version 91.0.4472.77. It was working perfectly before the update. selector.getAttribute('value') => now returns null Does anyone have an alternativ ...

Tips for choosing a dynamically generated ajax element

Question for you: I have a snippet of HTML code that looks like this: <li class='entry'> <div class='entryContent'> <p class='entryText'>Entry text></p> <a href="#" c ...

Converting coordinates of latitude and longitude into JSON format

I'm currently facing some challenges with organizing map waypoints, defined by latitude/longitude pairs, within a JSON array. This is the progress I've made so far. var llData = {}; var waypointData = {}; for (i = 0; i < routeArray.length; ...

Combining input streams using node.js and ffmpeg

Currently, I'm in the process of developing a basic and straightforward Video-Web-Chat platform. My approach involves utilizing the getUserMedia API call on the client side to capture webcam data and transmit it as data-blob to my server. My plan is ...

Which specific indexOf method is the most appropriate for my use case?

While exploring a codebase, I came across this code snippet that adds the indexOf function: if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(elt /*, from*/) { var len = this.length >>> 0; var from = Number(arguments ...

Interpreting an undefined HTTP GET request within a Node.js server

I am encountering an issue within my Node.js application. When I send an http get request through an ajax call on the client-side, the server-side does not recognize the request data and returns an "undefined" error message. This problem is puzzling to me ...

The Ajax readyState consistently displaying a value of 0

I am encountering an issue with my Ajax code as it always returns 0 when I access 'readyState'. I have not been able to identify the source of the problem yet. Any assistance on this matter would be greatly appreciated: var xhr = null; function ...

Retrieve the XML file from the webpage and save it to a specific directory using Java and the Selenium framework with the Chrome browser

Retrieve xml file from the website and save it to a specific location using java or selenium with Chrome browser. Here is the snippet of HTML code: <!-- Start of Code which handles XML Download--> <a href="javascript:downloadXML()"> <img s ...

Extracting web search result URLs using Puppeteer

I'm currently facing an issue with the code I've written for web scraping Google. Despite passing in a specific request, it is not returning the list of links as expected. I am unsure about what might be causing this problem. Could someone kindly ...

Using multiple selectors in JQuery and Javascript

I have a challenge where I need to execute different actions for specific divs. Here is the code snippet I currently have: $("#pending-cancel-1, #pending-cancel-2").click(function(){ Do something special for pending-cancel-1 and pending-cancel-2... }) ...

Utilizing JavaScript to Incorporate Node Packages

Sorry for the basic question, as I am fairly new to web development and JavaScript. I am trying to utilize a package that I installed via npm called shopify-buy by following the instructions provided at: The package is located in my node_modules director ...

Determining the most appropriate time to utilize the 'async' built-in function in ES2017 versus implementing 'npm i async' can depend on a variety of factors such

I recently discovered that async/await is a feature of ES2017, however, in some of my previous projects I had to use the package async to implement async/await functionality. Is there a simple way to determine when async can be used without importing it? ...

Include a header in every Apollo query

Looking to add a header to all queries and mutations using Apollo? You might be familiar with the common method: context: { headers: { 'Accept-Language': $this.i18n.current; } } However, this only applies to individual queries or mutatio ...