1
0
mirror of https://github.com/robonen/tools.git synced 2026-03-20 10:54:44 +00:00

feat(web/vue): add useStorage and useStorageAsync, separate all composables by categories

This commit is contained in:
2026-02-14 21:38:29 +07:00
parent 7dce7ed482
commit 6565fa3de8
64 changed files with 1564 additions and 55 deletions

View File

@@ -0,0 +1,38 @@
import { ref, watch, toValue, type MaybeRefOrGetter, type Ref, type WatchOptions } from 'vue';
export type Comparator<Value> = (a: Value, b: Value) => boolean;
/**
* @name useCached
* @category Reactivity
* @description Caches the value of an external ref and updates it only when the value changes
*
* @param {Ref<T>} externalValue Ref to cache
* @param {Comparator<T>} comparator Comparator function to compare the values
* @param {WatchOptions} watchOptions Watch options
* @returns {Ref<T>} Cached ref
*
* @example
* const externalValue = ref(0);
* const cachedValue = useCached(externalValue);
*
* @example
* const externalValue = ref(0);
* const cachedValue = useCached(externalValue, (a, b) => a === b, { immediate: true });
*
* @since 0.0.1
*/
export function useCached<Value = unknown>(
externalValue: MaybeRefOrGetter<Value>,
comparator: Comparator<Value> = (a, b) => a === b,
watchOptions?: WatchOptions,
): Ref<Value> {
const cached = ref(toValue(externalValue)) as Ref<Value>;
watch(() => toValue(externalValue), (value) => {
if (!comparator(value, cached.value))
cached.value = value;
}, watchOptions);
return cached;
}