Prevent the Vue page from loading until the data has been fetched successfully

I'm in the process of finding a way to prevent my page from loading until my fetch task is completed. I'm facing some issues that need to be addressed:

  • I have to re-fetch the data each time because I can't reuse the same data. (Changing views after it's loaded works, but reloading a route causes problems)
  • Anchor links are not functioning properly. For instance, if I have an anchor link #about located below some featured items, the #about section will be shifted lower because the featured items have just finished loading. It's challenging to implement a skeleton loading system as the number of items is dynamic.

Here is the current code I'm working on:

  data() {
    return {
      collections: [],
      items: []
    }
  },
  methods: {
    async fetchCollections() {
      const res = await fetch('http://localhost:4000/collections')
      return await res.json()
    },
    async fetchItems() {
      const res = await fetch('http://localhost:4000/items')
      return await res.json()
    }
  },
  async created() {
    this.collections = await this.fetchCollections()
    this.items = await this.fetchItems()
  }

I acknowledge that this approach may not be considered best practice and I might be making mistakes. Please offer constructive feedback rather than criticism, as I'm new to Vue and still improving my skills with JavaScript.

In summary

The desired outcome is for the page to complete loading only once the backend data has been retrieved.

Currently, the content pops up after a brief delay following the initial site load, which is not the intended behavior.

Answer №1

If you need to fetch data for your route, the recommended approach is to use Vue-router's Navigation guards. Check out the documentation for more information.
Below is some sample code that you can utilize:

async function fetchData() {
  const resCol = await fetch('http://localhost:4000/collections');
  const resColJson = await resCol.json();
  const resItems = await fetch('http://localhost:4000/items');
  const resItemsJson = await resItems.json();
  return { resColJson, resItemsJson };
}
export default {
  data() {
    return {
      collections: [],
      items: []
    }
  },
  beforeRouteEnter(to, from, next) {
    fetchData().then(({ resColJson, resItemsJson } ) => {
      next((vm) => {
        vm.collections = resColJson;
        vm.items = resItemsJson;
      });
    });
  },
  beforeRouteUpdate() {
    fetchData().then(({ resColJson, resItemsJson } ) => {
      this.collections = resColJson;
      this.items = resItemsJson;
    });
  },
}

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

Attempting to implement a typeguard in Typescript that relies on the presence of specific content within an element

Currently, I am attempting to develop a Typescript conditional that verifies if a particular word is already present in the name. The function in question is as follows: isOrganic() { for (let i = 0; i < this.items.length; i++) { if(this.ite ...

The necessity of the second parameter, inverseSide property in TypeORM's configurations, even though it is optional

As I delve into learning Typescript and TypeORM with NestJS simultaneously, a recent use-case involving the OneToMany and ManyToOne relation decorators caught my attention. It seems common practice for developers to include the OneToMany property as the se ...

Can we determine the data type of a value within a class instance by utilizing a function to retrieve it?

Is it feasible to create a function that maintains typing and functions in the same way as this: class Example { someNumber:number = 1; someString:string = "test"; } const example = new Example(); const value = example.someNumber; // typ ...

Tips for updating parameters that are defined in a controller within a promise

Currently, I am developing a single page application using Angular and TypeScript. I am facing an issue with updating the parameter value (_isShowFirst) of the controller inside a promise function. It seems like nothing is recognized within the promise blo ...

"Utilizing jQuery and Bootstrap 4 in TypeScript, attempting to close modal window using jQuery is not functioning

Trying to make use of jquery to close a bootstrap modal within an angular project using typescript code. The following is the code: function call in html: (click)="populaterfpfromsaved(i, createSaved, createProp)" createSaved and createProp are local ...

Title remains consistent | Angular 4

Struggling to change the document title on a specific route. The route is initially set with a default title. { path: 'artikel/:id/:slug', component: ArticleComponent, data: {title: 'Article', routeType: RouteType.ARTICLE, des ...

Vue JS encounters difficulties when attempting to lazy load various images from a randomized image URL

I've implemented a code snippet for lazy loading images with different URLs: <img src="https://source.unsplash.com/1600x900/?hotel,booking.com?v=1" loading="lazy" /> <img src="https://source.unsplash.com/1600x900/?hot ...

Prevent user input in Vue.js until the value has been modified

Need help handling initial input values: <input type="text" v-model="name" ref="input" /> <button type="submit" :disabled="$refs.input.defaultValue == $refs.input.value">Submit</button> Encountering an error with the disabled binding: C ...

My initial venture into Solidity DApp development, Encounter of an Unresolved Runtime

As I embark on developing my inaugural Solidity DApp using Next.js and Hardhat, I've encountered a perplexing error. After successfully deploying my contract on a local blockchain via npx hardhat node, the issue arises when calling the getProposalCoun ...

Utilize the data variable to dynamically generate components within the template

I have various components that share the same props. I'm looking for a solution to efficiently use these components within my template without having to resort to multiple if-else statements. To address this, I've created an object in my data whe ...

What steps should I take to address this issue using IONIC and TypeScript?

Running into an issue with my TypeScript code for an Ionic project. I'm attempting to pass the value of the variable (this.currentroom) from the getCurrentRoom() function to another function (getUser()) but it's not working. Here's my chat s ...

I'm interested in developing a feature that monitors a specific attribute and triggers a function once that attribute hits the value of 100

I am working on a function that will refresh the view once the percentage changes reaches 100: The value is stored in this variable: this.uploadPercent = task.percentageChanges(); This is the function I plan to implement : refreshView(){ Once this.uplo ...

Enhance JQuery functionality using Typescript

Currently, I am in the process of developing a Typescript plugin that generates a DOM for Header and attaches it to the page. This particular project utilizes JQuery for handling DOM operations. To customize the plugin further, I aim to transmit config Opt ...

Removing data from a table using an identifier in Typescript

Recently, I have made the switch from using Javascript to TypeScript. However, I am facing an issue while trying to delete data from a table in my code. Whenever I attempt to delete data, I encounter this error message: Property 'id' does not e ...

Can data from an Angular app be accessed by an external JavaScript code within the same project?

I've been thinking about a theoretical scenario that luckily I haven't encountered yet. Imagine I have an Angular Project compiled in My PROJECT FOLDER. <br/> Inside this PROJECT FOLDER, there's another JAVASCRIPT FILE external to ...

Implementing Angular's Advanced Filtering Across Multiple Data Fields

I am looking to create a custom filter for a list. Here is an example of the Array of Objects: myList: [ { "id": 1, "title":"title", "city":"city name", "types":[ { ...

The issue arises with Vue.http.get when using authorization, leading to two failed requests specifically on iOS

I am facing an issue with making authenticated HTTP requests using a bearer token. While it works perfectly fine on most platforms, I have noticed that certain iOS devices are experiencing a problem. fetchWithToken : function( endpoint, token ){ ret ...

What is the most effective way to determine the data type of a value associated with a key in an interface?

In my TypeScript interface, I have defined the following structure: MyInterface { 'key1': number | string; 'key2': string; 'key3': SomeOtherInterface; } I am looking to create a new type that utilizes the properties of ...

<T extends object>(value: T): T, but with the type changing from null to string

I discovered a tool called pathmirror that transforms objects like: {a: {b: null} } to {a: {b: 'a.b'} This is particularly useful for naming Redux actions. I'm wondering how I can create a type definition for this? Currently, my declarat ...

Having difficulty loading Angular2/ Tomcat resources, specifically the JS files

I am currently in the process of deploying my Angular2 web application on a Tomcat server. After running the ng build command, I have been generating a dist folder and uploading it to my Tomcat server. However, whenever I try to run my web app, I encounte ...