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

Packager freezing after running npm audit and the component directory is nonfunctional

Greetings, To begin with, I would like to acknowledge that this issue may have been addressed in previous posts, but despite following suggestions on Stack Overflow and GitHub, I am still facing two specific problems. Here are the issues I am encounterin ...

Building numerous pagination features in a single page using Codeigniter

I'm just starting out with codeigniter and I need help creating multiple paginations on one page. I've tried it, but only one pagination is working while the others are giving me errors. Can someone please assist me? I read some suggestions that ...

AngularJS Splice Function Used to Remove Selected Items from List

I previously inquired about a method to remove items from the Grid and received a solution involving the Filter method. However, I am specifically looking for a way to remove items using the Splice Function instead. You can find my original question here: ...

How can I show a tooltip in vuetify when a button is disabled?

I am currently using the button and tooltip components in my Vuetify project. I am trying to find a way to only display the tooltip when the button is disabled, but I'm having trouble figuring out how to do it correctly. Right now, the tooltip only a ...

Application Path-related Relative Path Problem in MVC Deployment

During the deployment of my MVC Project, I encountered a relative path issue in terms of the server. The project is being hosted as an application in IIS. Once deployed, the URL to access the application will resemble http://localhost/portal/Account/Login. ...

Use jQuery to dynamically update a text field within a table row based on a selection from

My understanding of JS and jQuery is not very strong. This is the HTML Output I created using a foreach-loop: $('#ProjectOfferPosition0IsystemTypeVariantId').on('change', function () { var prices = []; prices[1] = 500.00; ...

Node.js is throwing an error code 344, indicating that it is not possible to manipulate headers after they have already been

I'm still learning about Node and I've encountered this confusing error that I can't seem to figure out. I've searched for similar cases online, but none of them quite match mine. Any help would be greatly appreciated. From what I gathe ...

Is it possible to concurrently hot module reload both the server (.NET Core) and client (Angular)?

Using the command 'dotnet watch run' to monitor changes in server code and 'ng build --watch' for Angular code updates has been successful. It rebuilds the code correctly into directories "bin/" and "wwwroot/" respectively. myapp.cspro ...

Trying to access the 'style' property of a null value is causing an error

Although I have come across several questions related to this particular error, unfortunately, none of them provided a solution. Below is the HTML code: <!DOCTYPE html> <html> <head> <title>ChatRoom</title> <link ...

Tips for compressing JavaScript on the fly

Is there a method to dynamically compress JavaScript, similar to how gzip functions for HTML (and apparently CSS)? I'm looking for a solution where I don't have to manually compress the file before uploading every time. I want the server to hand ...

Looking for guidance on how to specify the angular direction in the ng-repeat

I am facing a challenge with the structure of my ng-repeat directive and I am having trouble navigating through it. Here is a representation of the data in array format JSON style {"data":[ ["sameer","1001", [ {"button_icon": ...

Can integer values be stored in localStorage similar to JavaScript objects and retrieved without requiring typecasting?

After setting an integer value to a localStorage item: localStorage.setItem('a', 1) and checking its data type: typeof(localStorage.a) "string" it shows as a string. I then typecast it to an int for my purposes: parseInt(localStorage.a) My ...

Failed to make a request to https://registry.npmjs.org/node-modules because of an error: error:0906D06C:PEM routines:PEM_read_bio:no start line

Encountering an issue while attempting to install a JS package. Despite conducting thorough research, I have not been able to resolve the error. Please help me identify where I am going wrong. npm ERR! request to https://registry.npmjs.org/node-modules ...

Issue with AngularJs failing to display data

As a newcomer to AngularJS, I am looking to utilize AngularJs to display the Json output from my MVC controller. Here is the code snippet for my MVC Controller that generates Json: [HttpGet] public JsonResult GetAllData() { ...

Tips for getting the sum of an array using the reduce method in Vue.js and returning the result array

As someone new to JavaScript, I apologize if my description of the issue is not clear. It's challenging for me to explain the problem I am facing. I have a computed function where I use the reduce method to iterate over my objects, perform calculatio ...

Retrieving Distinct Values in CouchDB

In my database, there are documents that represent different rooms. Each room has properties like "floor" and "hotel", among others. What I need to do is fetch all the floors associated with a specific hotel from the database. Something like getAllFloorsOn ...

Error found in event.PreventDefault()

I'm currently implementing Twitter Bootstrap on my application. I added e.preventDefault for the link button within $(document).ready(), but it doesn't seem to be functioning properly. Below is the code snippet: Master page: <a id="lnkLogou ...

Convert image buffer to string using Mongoose getter?

I have developed a basic node backend application modeled after eBay. I am now working on creating a react frontend app to complement it. Within the app, users can list items for sale and include a photo with their listing. The item information is stored ...

Save the output of Html.Raw() into a JavaScript variable when using ASP.NET MVC 3

One issue I'm encountering in my ASP.NET project involves retrieving a string of HTML from the database and assigning it to a client-side variable. Currently, I am using the following code: var x = '@Html.Raw(myModel.FishValue)' This work ...

Challenge with maintaining tab view data in Openui5

I am facing an issue with my application's tabs. Each tab renders data retrieved through ajax calls from the database. However, whenever I switch between tabs, the data gets refreshed each time. Is there a way to prevent this refreshing behavior and i ...