[Vuejs]-Vue JS: API call request on app.vue in single page application

0👍

Yes, you can call the API a single time in the component that contains router-view and pass down the results to rendered components through props. The rendered components must declare the props that will be passed down to them, but only if they will be using it.

<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>

But if the API call returns a huge amount of data or is really slow, then I really suggest that you check into optimizing the backend queries of your API, paginating results, and loading them progressively with lazy load on scroll or something.

Also it would be good if you can keep something in your state to check if the data is being loaded or not, so that you can show a loader or something rather than a white page until you get the results.

0👍

One possible solution is to adapt getBuildings(), such that it will call the backend only once and store the result in a property of BuildingsService, e.g. cachedBuildings.

If cachedBuildings is empty, getBuildings() calls the backend and stores the result in cachedBuildings.

If cachedBuildings is not empty, getBuildings() returns cachedBuildings.

The advantage of this solution is, that you only adapt your code in one place and the caching is transparent for every component.

Leave a comment