'vue3 how to use suspense passing async props to component
I've been learning about suspense but I still don't figure out how to use it in my use case.
I understand how to use it when you have a component which has the responsibility to fetch data itself, but I show a legacy example which I don't know how to migrate:
ExampleView.vue
<template>
<skeleton-component v-if="isLoading && !hasError">
<alert-component v-if="hasError">
<example-sub-component v-if="!isLoading && !hasError" :data=data />
</template>
<script setup>
const isLoading = ref(true)
const hasError = ref(false)
const data ref(null)
fetchData().then((response) => {
data.value = response
}).catch((e) => {
hasError.value = e
}).finally(() => {
isLoading.value = false
})
</script>
ExampleSubComponent.vue
<template>
{{data}}
</template>
<script setup>
defineProps([data])
</script>
Can I use suspense to simplify my code? I thought suspense would remove all this kind of logic about loading and showing/hiding errors.
But the only way I see to accomplish this is moving the fetchData logic inside ExampleSubComponent
but I don't like this approach... In my use case I feel it's the view who has to fetch the data and pass down to components.
I tried this code but not working... suspense is looking for ExampleSubComponent
to be async but it's not, the only async logic is the fetchData.
ExampleView.vue
<template>
<suspense>
<template #default>
<example-sub-component v-if="!hasError" :data=data />
<alert-component v-if="hasError">
</template>
<template #fallback>
<slot name="fallback">
<skeleton-component>
</slot>
</template>
</suspense>
</template>
<script setup>
const hasError = ref(false)
const data ref(null)
await fetchData().then((response) => {
data.value = response
}).catch((e) => {
hasError.value = e
})
</script>
I will need to still write this loading/showing hiding errors logic in every view?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|