Implementing an API call in Vue JS on the app.vue component of a single page application

My project is experiencing delays in API requests due to a large amount of data. I have tried adding a cache, but the page still appears white upon creation. I am considering moving the API call to app.vue to speed up the request. Is there a way to do this? Currently, I make an API request on each page in my project.

//building.vue where buildings api used

<template>
    <b-row class="icon-examples">
              
             
              <b-col lg="3" md="6"  v-for="(building, index) in buildings"
              :key="index" >
                
                <button type="button" class="btn-icon-clipboard" @click="GoToBuilding(building._id)"
      >
                  <div>
                    <i class="ni ni-building"></i>
                <router-link
                  class="question-routerToDetail"
                  :to="`/tables/${building._id}`"
                >      <span > B info - </span>
                    <span>{{building.building_number}}</span></router-link>
                  </div>
                </button>
              </b-col>
         

            </b-row>
</template>

<script>
import BuildingsService from "../../../services/ApiService"
export default {

    data() {
        return {
  

   
        };
    },
    components: {
      props:
  ['buildings'],
       
      BaseHeader,
      //  buildings:[]
    },
 

    }
}
</script>

app.vue:

<template>
  
<router-view :number="count" @send="getNewCount"   @reset="onReset" :buildings="buildings">

<sidebar :number="count" @reset="onReset"/>

</router-view>
</template>
<script>

export default {
components: {
    sidebar,

  },
    data() {
        return {
         buildings: []
      };
        
    },
         
    created(){
    BuildingsService.getBuildings().then((response) => {
                this.buildings = response.data.response;
                 console.log(this.buildings , "skk")
            });

          }
}
</script>

Is it possible to save the API request array in app.vue and use it on other pages? Will this improve my API call efficiency?

Thank you in advance

Edit: Updated question based on answer below... but receiving empty data with no console errors

Answer №1

A single API call can be made in the component containing the router-view, and then the results can be passed down to rendered components through props. It is important for the rendered components to declare the props that will be utilized.

<template>
    <router-view :number="count" 
        @send="getNewCount" @reset="onReset"
        :buildings="buildings">
        <sidebar :number="count" @reset="onReset"/>
    </router-view>
</template>
<script>
    import BuildingsService from "../../../services/ApiService"
    export default {
        components: {
            sidebar,
        },
        data() {
            return {
                buildings: []
            };
        },
        created(){ 
            BuildingsService.getBuildings().then((response) => {
                this.buildings = response.data.response;
            });
        }
    }
</script>

If the API call returns a large amount of data or is slow, consider optimizing backend queries, pagination, and implementing lazy loading on scroll. Including a loading indicator in your state to indicate when data is being fetched can improve user experience.

Answer №2

An effective approach would be to modify the getBuildings() function so that it only contacts the backend once and stores the data in a property called cachedBuildings within BuildingsService.

If cachedBuildings is currently empty, getBuildings() will fetch the data from the backend and save it into cachedBuildings.

If cachedBuildings already contains data, getBuildings() will simply return the cached information.

The benefit of this solution lies in its simplicity - you only need to make adjustments in one location, and the caching process works seamlessly across all components.

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

Failure of AJAX HTML function to retrieve value from textarea

I am displaying data in the first three columns of a table, with the last column reserved for user feedback/comments. However, when the form is submitted, the values in the textarea are not being posted. The table has 6 rows. The Sample TR: <tr> &l ...

JQuery form plugin experiencing issues with Ajax functionality

I am facing an issue with implementing the Jquery form plugin using ajax to insert my form data into the database. Although the validation is working correctly, the ajax call is not receiving any data in response. It seems like I might not be following the ...

Display a spinning wheel or progress bar while the website is in the process of loading

Looking to construct a treeview using the jquery-treeview plugin but noticing it's quite time-consuming (about 5-7 seconds). I'm interested in adding a spinning wheel or progress bar to indicate loading while the page is processing. Any suggestio ...

What is the connection between importing and using destructuring in ES6 syntax?

Bring in: import React, { Component } from 'react'; Unpacking: let z, { b } = {a: 1, b: 2, c: 3} Both of these examples seem to have similar syntax. However, in the second example, z will be undefined instead of {a: 1, b: 2, c: 3}. Does this ...

Elegant bespoke input box

I am looking to create a customized input text feature similar to StackOverflow's tag editor, but with some minor differences. The goal is for the input field to function like a regular text input until a word is enclosed in curly brackets. Once enclo ...

Modifying the appearance and behavior of an element dynamically as the page is being loaded using AngularJS

Struggling with a challenge for two days now, I have attempted to implement a panel-box using bootstrap and AngularJS. Within the confines of a controller, my code looks like this: <div id="menu2a"> <div class="panel list-group"> <div ...

Sveltejs template not displaying on M1 MacBook Air after running - stuck on blank screen

Currently, I am in the process of learning Sveltejs and have been utilizing for the tutorial, which has been quite effective. However, I decided to work on developing and testing Sveltejs applications locally on my MacBook Air M1. I downloaded the provid ...

Introduce new router events, routeChangeStart and routeChangeComplete, within the client-side components of next js 14

I am currently working on a Next.js v14.0.4 project and I am facing an issue with implementing a top loader progress bar using the NProgress package for route changes triggered by Link or router.push(). The handleRouteChangeStart and handleRouteChangeCom ...

React.js "universal" component that is able to be generated multiple instances of

I'm struggling to fully understand this problem. Here's the issue: imagine there is an app where I need to generate notifications, dialogs, or other similar elements from my code. One option is to have a "global" component that controls everyth ...

Retrieve various elements using a loop and dynamic identifiers (perhaps within a multi-dimensional array)

Apologies for the confusing title. I am currently working on a piece of code which can be found here: https://jsfiddle.net/8ers54s9/13/ This code creates a basic text area and compares it to a predefined array to identify common words within a string. If ...

In ES6, instantiate a fresh new instance of this

Can a new instance of self/this be generated using ES6 inside a static method? For instance; class myClass { static model() { return new this; } } Is there a standard approach for this situation? Thank you very much. ...

removing vue dynamic component before it is destroyed

Is there a way to display an alert message before switching components? (Using `beforeDestroy` doesn't work until the path is changed...) <template> <keep-alive> <component :is="dynamicComponent" /> </keep-alive& ...

Transform a string into an array using JavaScript

Currently, I am dealing with an array: itemSku = ["MY_SERVICE","SKU_A","SKU_B"]; When passing this value to a component in Angular, the type of itemSku is being identified as a string. This prevents me from performing array operations on it. console.log ...

dynamic image size based on mobile device orientation

Struggling with a tiny mobile image gallery here. Whenever I switch to portrait mode, the images end up being too big for the screen. Is there a way to use javascript to resize the images to fit the screen when switching to portrait mode? They display fin ...

The error message for an onclick event in HTML/JavaScript references a ReferenceError, and also involves issues with

Currently, I am working on creating a simple text-based golf game as a coding exercise. This game does not involve any trigonometry; instead, it relies on randomness to determine how hard the ball is hit and how many shots are required to reach the hole. A ...

What's the best way to incorporate a clear options icon when choosing an option in a MaterialUI select component?

I am looking to enhance the user experience by adding a clear options icon that appears when a selection is made from the list of options. <Select InputProps={{ startAdornment: ( <InputAdornment position='end'> <Cl ...

At times, Express.js may display an error message stating "Cannot GET /"

My objective is to have http://localhost:3000/app display myFile.html and http://localhost:3000/api return "It worked!". I currently have two files set up for this: App.js: const http = require('http'); const fs = require('fs&apo ...

When the route is changed, the system must execute a function to verify the authenticity of the token

When routing changes in Angular, I have a requirement to execute a function based on whether a valid token is set or not. Is there anyone who can assist me in achieving this task? In Angular 1, I used to accomplish this using $on. ...

What could be causing my div to not appear when using jquery's show function?

I'm dealing with HTML code that looks like this: <div id="answerTypeSection" style="visibility: hidden"> <div class="row"> <div class="col-md-2">adfadfafasdfasdfas</div> </div> <label class="control-label"&g ...

Tips for sending and retrieving parameters using the POST technique

Currently, I am in the process of building a user authentication form for my website using Javascript. I am utilizing Vue JS on the client-side and NodeJS with ExpressJS on the server-side. For the server-side functionality, I have implemented the followi ...