Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Best practice of structuring data in a vue app

I have several views in my vue project. Some of these have the same component in them which will display the same data. At the moment I am getting the data in the components when they are mounted. Should I be getting the data higher up so it is only fetched once if it is the same to minimise requests? I’m not sure what is best practice for this. Thanks

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’m not fond of any store/global state management.
They are just singletons for me. In ESM a module is kinda a singleton, so put your data in a module and use it in any place you want 🙂

data.js:

import {reactive} from 'vue'
import api from './api.js'

let loadingPromise;
const data = reactive({
   // enter some default values to display or mark it as not loaded
   loaded: false
})

export function loadData(){
    // start loading data when first demanded
    loadingPromise ??= api.get('my-endpoint')
    // this will update your components reactively
    .then(responseData => Object.assign(data, responseData, {loaded: true})) 
    
    return data; // just return the reactive data even if it's not loaded yet

}

Component.vue

<script setup>

import {loadData} from './data.js'

const data = loadData()

</script>
<template>
<div v-if="!data.loaded">Not loaded yet...</div>
<div v-else>
<!-- display your component content here -->
</div>
</template>

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading