useFallback: Reactive nullish coalescing operator
See original GitHub issueClear and concise description of the problem
~I want logicalOr
, but with the nullish coalescing operator (??
).~
I want to write fallback code. As @thedamon pointed out below, nullish coalescing isn’t what we want because we want to be able to short-circuit the fallback with an explicit null
.
Context
I’m writing a lot of universal fallback code to check if a user has passed in props.modelValue
or props.value
so that my component code is backwards compatible.
This ends up with me writing:
const val = computed(() => props.modelValue ?? props.value)
// pass into useVModel(val), etc.
in a lot of components.
Suggested solution
A function called useFallback which would take in args.
Usage
const props = defineProps<{
someValue: string
deprecatedValue: string
defaultValue: string
}>()
const resolvedValue = useFallback(props.someValue,
props.deprecatedValue,
props.defaultValue)
Alternative
We could pass in the entire props
object and use an Array, like useVModel
does.
Additional context
Honestly, I’m just looking for a concise way to declare fallbacks for two values: modelValue
and value
.
The better solution to my problem is probably to make a feature request to useVModel
so that it also handles the emit
backwards compatibility.
Validations
- Follow our Code of Conduct
- Read the Contributing Guidelines.
- Read the docs.
- Check that there isn’t already an issue that request the same feature to avoid creating a duplicate.
Issue Analytics
- State:
- Created a year ago
- Reactions:4
- Comments:8 (5 by maintainers)
Top GitHub Comments
Is there appetite to bake some of the ‘vue-bridge’ type functionality into VueUse? then it could maybe be as direct as
useBridgedVModel
which would be a separate as necessary but potentially reusing the vueUse function bridgified version ofuseVModel
?That’s a good point. In which case,
useFallback
isn’t really gonna use the nullish coalescing operator, it will let you short-circuit with an explicitnull
.We should open another feature request for
logicalNullish
ornullish
and that’ll go in the@vueuse/math
package.