I’ve got the following component:
<template>
<Grid :items="items" />
</template>
<script setup>
import { ref, onMounted } from 'vue'
import Grid from '@/components/Grid.vue'
import { getData } from '@/services/getData'
const items = ref()
onMounted(async () => {
items.value = await getData()
})
</script>
The Grid
component instance needs items
to be populated in order to display data, but I need to run getData()
to have the data ready. When I run this code I get a type check failed for prop "items". Expected Object, got Undefined
warning.
It happens because when the file is first initiated items
doesn’t have anything until getData()
is finished. How can I have getData()
run before the warning can show up?
2
Answers
Before the data is loaded your
items.value
isundefined
so causing the error.Initialize it to
where
<object>
is your appropriate format to feed the grid initially (either an object (with particular format or empty) or an array).If
Grid
relies on a value, it shouldn’t be rendered until a value is initialized.It’s either:
Or:
The latter options makes the component async and requires to use
<Suspense>
in parent components.