skip to Main Content

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


  1. Before the data is loaded your items.value is undefined so causing the error.
    Initialize it to

    const items = ref(<object>)
    

    where <object> is your appropriate format to feed the grid initially (either an object (with particular format or empty) or an array).

    Login or Signup to reply.
  2. If Grid relies on a value, it shouldn’t be rendered until a value is initialized.

    It’s either:

    <Grid v-if="items" :items="items" />
    

    Or:

    const items = ref()
    items.value = await getData()
    

    The latter options makes the component async and requires to use <Suspense> in parent components.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search