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