Within my Vue project, I am utilizing a ref
variable that stores data retrieved from a database. This reference is contained within Pinia's setup store for easy access.
The objective is to load the data only when requested by the user and then always provide it once it is loaded, in order to prevent unnecessary database queries. Here is a potential approach:
// Implement the "ref" smartly <- TODO
const myRef = ref(
// something like:
// return myRef ?? readMyRefFromDB();
);
...
// User requests the value
console.log(myRef.value); // <- initial request: retrieve from DB and assign to value property
...
// User accesses the value again
console.log(myRef.value); // <- subsequent requests: no need to query DB, return stored value
Currently, my method involves calling readMyRefFromDB
whenever myRef.value
needs to be accessed. While this works, it requires at least two lines of code and can lead to errors with frequent use.
An alternative solution could involve using a computed
getter. However, accessing the property from within its own getter may pose a challenge. One potential workaround is to utilize a dummy ref
that gets filled within the computed
function of myRef
, though this approach may not be ideal:
const dummyRef = ref();
const myRef = computed(() => dummyRef.value ?? readMyRefFromDB());
function readMyRefFromDB() {
dummyRef.value = db.load('myRef')
return dummyRef.value;
}
...
// User exclusively accesses myRef
console.log(myRef.value);
Are there better, more Vue-friendly approaches to tackling this issue?