Onyx
Onyx

Reputation: 5782

How to avoid getting "TypeError: Cannot read property 'weekday_text' of undefined" error when some objects have the field and some don't?

I'm getting the sight information by making a GET request to google places API. Unfortunately, some sights have a opening_hours object field which itself has weekday_text and open_now fields BUT some of the sights don't so I get the error

<p v-if='sight.opening_hours && sight.opening_hours.open_now'>Open now</p>
<p v-if='sight.opening_hours && !sight.opening_hours.open_now'>Closed now</p>
<p v-if='sight.opening_hours && sight.opening_hours.weekday_text' v-for='day in this.sight.opening_hours.weekday_text'>{{ day }}</p>

Are my v-ifs not covering the case where sight.opening_hours and sight.opening_hours.weekday_text do not exists? I think the error comes from the v-for since if I remove it, everything works fine.

Upvotes: 1

Views: 106

Answers (2)

ma_dev_15
ma_dev_15

Reputation: 1196

https://v2.vuejs.org/v2/guide/conditional.html#v-if-with-v-for v-if and v-for together is not recommended

<div v-if='sight.opening_hours && sight.opening_hours.weekday_text'>
  <p v-for='day in this.sight.opening_hours.weekday_text'>{{ day }}</p>
</div>

or if you don't need to print div then you can use template

<template v-if="sight.opening_hours && sight.opening_hours.weekday_text">
  <p v-for='day in this.sight.opening_hours.weekday_text'>{{ day }}</p>
</template>

Upvotes: 1

Sergey Shapirenko
Sergey Shapirenko

Reputation: 165

You need to rewrite your code like 'condition check on outer level and iteration inside'. You probably need template element.

template(v-if="sight.opening_hours && sight.opening_hours.weekday_text")
  p(
    v-for="(day, index) in this.sight.opening_hours.weekday_text",
    :key="index"
  )
    | {{ day }}

Upvotes: 1

Related Questions