-
Hi Everyone, I came across an error in Vue when using
As you can see in this example, there is a Example: https://stackblitz.com/edit/vue3-ts-use-observable?file=src/components/Example.vue As noted in the code, there are a few ways around this...
Example of approach 2... const foo = useObservable(apiCall$.pipe(map(({ data }) => data.nested.foo )))
const bar = useObservable(apiCall$.pipe(map(({ data }) => data.nested.bar ))) I'm tending to lean more towards the second approach for these reasons:
What is your opinion? What is best practices for handling observables with nested objects from API calls leveraging subscriptions e.g. firestore? How to handle defaults elegantly during the stale period where observables haven't emitted any values? Inspiration for |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 5 replies
-
Why I think this surrounds a bugAt a glance, this is a bug in the type signature of Interestingly enough, this seems to be the case becuase the next line declares a ref of the correct type but by the time it is returned, it incorrectly casts away. How is this solved in other ecosystems (Flutter)In Dart, where Streams are first class, the authors of the Flutter equivalent of VueUse allow you to provide an
This ensures that it always returns a As for how to handle this in Real AppsWhen your Ref from useObservable is undefined, you typically need to handle this in your Vue Template. I think your option 1 and option 2 are fine possibilities, however there are a few more options. Option 3 (my fav)Why would it ever be undefined? Because it's loading! That's a state your component likely needs to handle gracefully. <script setup>
const yourApiCallData = useObservable(apiCall$)
const isLoading = computed(() => yourApiCallData === undefined)
</script>
<template>
<div v-if="isLoading">
Loading!
</div>
<div v-else>
{{yourApiCallData.firstName}}
No null ref errors, because yourApiCallData will never be null.
</div>
</template>
Option 4 (with new proposed API)<script setup>
const yourApiCallData = useObservable(apiCall$, {initialData: {firstName: ''}})
</script>
<template>
<div>
{{yourApiCallData.firstName}}
No null ref errors, because yourApiCallData will never be null.
</div>
</template> |
Beta Was this translation helpful? Give feedback.
Why I think this surrounds a bug
At a glance, this is a bug in the type signature of
useObservable
. The type signature says that it returnsRef<H>
but per your example it obviously returnsRef<H | undefined>
.Interestingly enough, this seems to be the case becuase the next line declares a ref of the correct type but by the time it is returned, it incorrectly casts away.
How is this solved in other ecosystems (Flutter)
In Dart, where Streams are first class, the authors of the Flutter equivalent of VueUse allow you to provide an
initialData
const count = useObservable(myCount$, {initialData: 0})
This ensures that it always returns a
Ref<number>
otherwise it returnsRef<number | undefined>
A…