Reputation: 431
I'm using Vue3 with Nuxt3 (universal rendering) and here is code for my page:
<!-- /pages/search.vue -->
<script setup>
const route = useRoute();
const {pending, data} = await useLazyFetch(
"api/car-models"
+ `?start-date=${route.query.startDate}`
+ `&end-date=${route.query.endDate}`,
);
</script>
<template>
<div v-if="pending">
Loading...
</div>
<div v-else-if="data.carModels.length === 0">
Sorry, no cars available for the selected dates and location.
</div>
<div v-else>
<ul>
<li v-for="car in data.carModels">
<CarCard :car="car"/>
</li>
</ul>
</div>
</template>
it works fine, and CarCard
s are showing when i navigate to page. But when i hit refresh, I get
500
Cannot read properties of null (reading 'carModels')
at ...
Why I get this error/exception only after reload and how can I fix it?
Thanks.
Upvotes: 0
Views: 1533
Reputation: 735
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
Upvotes: 0