[Vuejs]-Cannot read properties of null in Vue

0👍

Straight from the docs:

<template>
  <!-- you will need to handle a loading state -->
  <div v-if="pending">
    Loading ...
  </div>
  <div v-else>
    <div v-for="post in posts">
      <!-- do something -->
    </div>
  </div>
</template>

<script setup>
const { pending, data: posts } = await useLazyFetch('/api/posts')
watch(posts, (newPosts) => {
  // Because posts might start out null, you will not have access
  // to its contents immediately, but you can watch it.
})
</script>

The reason you get an error is because at first the result is null. You could just write v-else-if="data?.carModels.length === 0" with the question mark to automatically check for null, but you should still have to watch your data to update the result to show.

Docs: https://nuxt.com/docs/getting-started/data-fetching#uselazyfetch

Leave a comment