This commit changes `WatchSource` signatures into `Readonly<Ref>`s.
It provides two important benefits:
1. Eliminates the possibility of `undefined` states, that's result of
using `WatchSource`s. This previously required additional null checks.
By using `Readonly<Ref>`, the state handling becomes simpler and less
susceptible to null errors.
2. Optimizes performance by using references:
- Avoids the reactive layer of `computed` references when not needed.
- The `watch` syntax, such as `watch(() => ref.value)`, can introduce
side effects. For example, it does not account for `triggerRef` in
scenarios where the value remains unchanged, preventing the watcher
from running (vuejs/core#9579).
21 lines
515 B
TypeScript
21 lines
515 B
TypeScript
import { WatchSource, watch } from 'vue';
|
|
|
|
export function waitForValueChange<T>(
|
|
valueWatcher: WatchSource<T>,
|
|
timeoutMs = 2000,
|
|
): Promise<T> {
|
|
return new Promise<T>((resolve, reject) => {
|
|
const unwatch = watch(valueWatcher, (newValue, oldValue) => {
|
|
if (newValue !== oldValue) {
|
|
unwatch();
|
|
resolve(newValue);
|
|
}
|
|
}, { immediate: false });
|
|
|
|
setTimeout(() => {
|
|
unwatch();
|
|
reject(new Error('Timeout waiting for value to change.'));
|
|
}, timeoutMs);
|
|
});
|
|
}
|