Load value in ref only when requested in Vue

48 Views Asked by At

In my Vue project, I have a ref variable that contains some data loaded from a DB. As a reference, it lives inside a Pinia's setup store.

My goal is to load the value only when requested by user, and then always return it once it is loaded, to avoid unneded DB access. The approach would be like:

// Create the "ref" in a smart way <- TODO
const myRef = ref(
  // something like:
  // return myRef ?? readMyRefFromDB();
);

...

// User access the value
console.log(myRef.value); // <- first usage: access DB and fill value property

...

// User re-access the value
console.log(myRef.value); // <- next usage: no need to access DB, return value

Currently, my approach is that, whenever one needs to access myRef.value I firstly call readMyRefFromDB, which does nothing if value already exists. However, this forces me to always use at least 2 lines to do it, and it's very error prone when used several times.

Another approach I can think of is to use computed getter, however I'd need to access property from inside its own getter, and that should not be possible. A possible solution might then be to use a dummy ref that gets populated inside the computed of myRef, but might not be ideal:

const dummyRef = ref();

const myRef = computed(() => dummyRef.value ?? readMyRefFromDB());

function readMyRefFromDB() {
  dummyRef.value = db.load('myRef')
  return dummyRef.value;
}

...

// User only accesses myRef
console.log(myRef.value);

Is there a better (Vue-friendly) approach?

1

There are 1 best solutions below

1
MattP On

Although you could build something like this yourself, you might consider checking out VueUse for the computedAsync function. Specifically, you might want the lazy option described here.

The library is high quality, and we are using it extensively in our projects. Many features available beyond this specific need.