Created
January 3, 2025 08:53
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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