How to initialise computed with a default value? #14947
-
|
I'm trying to do the following:
const computedWithCache = <K extends keyof CachedState>(key: K, getter: () => CachedState[K]) => {
const cachedValue: CachedState[K] = cache.get(key);
return computed<CachedState[K]>(() => (isEmpty(getter()) ? cachedValue : getter()));
};
const referenceRef = ref(null);
const finalComputed = computedWithCache('someCacheKey', () => referenceRef.value);
// should return cachedValue
finalComputed.value;
referenceRef.value = 'something';
// should return referenceRef.value
finalComputed.value;
referenceRef.value = null;
// should still be bound to the referenceRef and return "null"
finalComputed.value;However it's losing its reactivity on the pass where the Is there a way to achieve that? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
|
You need to always access Calling getter() once and storing the result... - -you still return cachedValue when it's empty -when -when it goes back to null, the computed re-runs again and returns null |
Beta Was this translation helpful? Give feedback.
You need to always access
referenceRefreactively, regardless of which value you return. The trick is seperating your logic.Calling getter() once and storing the result...
-
referenceRefis always accessed on every execution, Vue always registers it as a dependency-you still return cachedValue when it's empty
-when
referenceRefchanges to something non-empty,…