Skip to content

Instantly share code, notes, and snippets.

@alexmccabe
Created January 3, 2025 08:53
Show Gist options
  • Save alexmccabe/b959c5fb0a1bc897769284c6d50e7f09 to your computer and use it in GitHub Desktop.
Save alexmccabe/b959c5fb0a1bc897769284c6d50e7f09 to your computer and use it in GitHub Desktop.
A utility function to deep unref Vue reactive entities. Adapted from vue-deepunref, but now with types and slightly more concise code
export function deepUnref<TInput>(val: MaybeRef<TInput>): TInput {
const checkedVal = isRef(val) ? unref(val) : val;
if (!isPlainObject(checkedVal)) {
return checkedVal;
}
if (Array.isArray(checkedVal)) {
return checkedVal.map(deepUnref) as TInput;
}
return unrefObject(checkedVal);
}
function smartUnref<TVal>(val: MaybeRef<TVal>): TVal {
if (val !== null && !isRef(val) && typeof val === 'object') {
return deepUnref(val);
}
return unref(val);
}
function unrefObject<TObj extends Record<string, unknown>>(obj: TObj) {
const mapped = objectKeys(obj).map((key) => {
return [key, smartUnref(obj[key])];
});
return Object.fromEntries(mapped);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment