I am trying to learn Vue and am having trouble with conditional rendering. It is not breaking the app but it's giving me a console error.
Initially, character is an empty object.
I am trying to only render the card when a character exists (when a button is pressed). Currently I am getting the error
Error in render: "TypeError: Cannot read property 'length' of undefined"
Currently a card does not render until it is supposed to, but it is giving me those errors.
My Component is:
<template>
<v-card v-if="character" min-width="350" outlined>
<div class="d-flex flex-no-wrap justify-space-between">
<v-avatar class="ma-3" size="125" tile>
<v-img :src="character.image"></v-img>
</v-avatar>
<div>
<v-card-title class="secondary--text text-h6">{{
character.name
}}</v-card-title>
<v-card-subtitle class="secondary--text"
>Featured in {{ character.episode.length }} episodes</v-card-subtitle
>
<v-card-subtitle class="secondary--text pb-0 pt-0">{{
character.species
}}</v-card-subtitle>
<br />
<v-card-subtitle class="secondary--text pt-0"
>Origin: {{ character.origin.name }}</v-card-subtitle
>
</div>
</div>
</v-card>
<div v-else></div>
</template>
<script>
import { mapGetters } from 'vuex';
export default {
name: 'CharacterCard',
computed: mapGetters(['character'])
};
</script>
You said
Initially, character is an empty object.
and then you are trying to access character.episode.length
which is giving the error "TypeError: Cannot read property 'length' of undefined"
because character.episode
is undefined, which has no property 'length'
There are several potential solutions. Here are a few:
(character.episode || []).length
character.episode && character.episode.length || 0
character.episode?.length || 0
note - may require some babel magic to get optional chaining to work. see: https://forum.vuejs.org/t/does-vue-cli-3-come-with-pre-configured-optional-chaining/42609You could either put this directly in the template in-line, or it would may be better to put it in a computed property.