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

Update the array state based on the selection of checkboxes and user input in real-time

In my current project using react js, I am working on a UI development task where I need to create a dynamic table based on data fetched from an API. Each row in the table includes a checkbox and a text input field that are dynamically generated. My goal i ...

Search for Div IDs while filtering as you type

Is there a search jQuery plugin that enables real-time filtering based on Div ID as you type in the search box? It would be great if the filter instantly refreshes. ...

What is the best approach to perform a search in mongoose based on specific query parameters?

I have a form that allows users to search for transactions by specifying the buyer name, item name, or both. This means I can receive any of these queries: localhost:8000/allPayments/?i=pasta localhost:8000/allPayments/?b=Youssef localhost:8000/ ...

Enhancing Pinia setup stores with custom getters, setters, and actions for improved reusability

If we think about a Pinia setup store that has a basic set of state, getters, and actions in place: export const useBaseStore = defineStore('base-store', () => { const name = ref<string>(''); const age = ref<number>(1 ...

implement a user input field within a div using JavaScript

I have created a lightbox in my HTML page with the following structure: <div id="container"> <input type="text" id="user_1" name="user_1" value="user_1"/><br> <input type="text" id="user_2" name="user_2" value="user_2"/>< ...

Update the information for every ride to include an appropriate park_id instead of the `park_name` property

I created a function that takes an array of objects and modifies one of the object's names to its corresponding property id. Here is the function implementation: function prepareRidesData(rides, parks) { if (!rides.length) return []; const parksL ...

Having trouble getting two components to return in React

After successfully implementing the Hello World example by returning "Hello" and "world" from two different components, I encountered a problem with my code. In this specific code snippet, I am unable to return the Menubar component, although the Map compo ...

The functionalities of $scope and this in AngularJS

Currently, I am developing a small application using angularjs. In this project, I am trying to implement a feature that involves deleting a contact. The functionality itself works perfectly fine, however, I am encountering an issue where the 'this.op ...

The Node.js execSync functionality is not functioning as expected, as the changes made to the system are not taking effect

I'm looking to prevent chrome.exe from accessing the internet through the Windows firewall. The specific command I need to use is netsh advfirewall firewall add rule name="Block Chrome" dir=out action=block program="C:\Program Files (x86)\G ...

Updating a URL once AngularJS has finished processing it

Currently, I am utilizing Primo, an AngularJS app developed by Ex Libris. This application functions as a library catalog, enabling users to explore both physical and digital collections within the library. Despite not having direct access to the original ...

Utilizing the power of Vue.js and D3.js in tandem to create dynamic force simulations

Currently, I am attempting to retrieve data from a Restful API call and utilize it to create a d3.js force simulation. However, I have encountered an issue where if I use the data from the API call directly, the simulation treats it as if there is no data ...

Exploring the concept of union types and typeguards in TypeScript

I'm struggling with this code snippet: function test(): any[] | string { return [1,2] } let obj: any[] = test(); When I try to run it in vscode, I get the following error message: [ts] Type 'string | any[]' is not assignable to type & ...

Develop a scrambled PHP webpage for a CAPTCHA system

I've implemented the cool-captcha feature in my registration form. Here's the code snippet that generates the Captcha image: <img src="captcha.php" id="captcha" /> However, there is an issue where anyone can easily access the "captcha.ph ...

The express-fileupload throws an error saying "ENOENT: unable to locate the file or directory at 'public/images/name.ext'"

I am encountering an error ENOENT: no such file or directory, open 'public/images/name.ext from express-fileupload. I have searched for solutions to this issue, but none of the ones I found seem to work for me. Here are two examples: No such file or d ...

jquery dialog content vanishing upon second opening

My jQuery code is set up to display a dialog when a button is clicked. The issue I'm experiencing is that after closing the dialog and reopening it, the text area within the dialog appears empty with only three buttons visible. However, upon subsequen ...

activate a specific tab within a tab container using JavaScript

Having an issue with the JavaScript function below that I am using to set active ASP.NET tabs. Whenever I run the code, it always returns CurrentTab as "null". Can anyone help me solve this problem? function SetActiveTab2(tabNumber) { try { ...

Unable to vertically scroll on a position fixed element

I recently created a unique VueJS component that enables vertical scrolling. Within this component, there are two elements each with a height of 100vh. At the bottom of the component is a fixed position div. Interestingly, when I try to scroll down using m ...

What is the correct way to utilize ng-if/ng-show/ng-hide to hide or show HTML elements within the app.run function

I am currently working on developing an app that loads views correctly. HTML: <body> <loading outerWidth='1000' outerHeight='1000' display='isReady'></loading> <div class='wrapper' ng-sho ...

Is there a way to prevent my token from being exposed when making an AJAX call?

When working on my HTML file, I encountered an issue with a Python Django URL integration where I need to pass a token to retrieve certain information. However, the problem is that my token is exposed when inspecting the page source in the HTML document. ...

ways to run php script based on screen resolution or size

I have 2 php files that I need to execute based on screen size. include_once('large.php'); include_once('small.php'); The condition is to run large.php when the screen size is greater than 992px, and small.php when the screen size is ...