Reputation: 99
In the console of my website, I see the following error:
vue.esm.js?a026:628 [Vue warn]: Error in render: "TypeError: Cannot read property 'id' of undefined"
found in
---> <ApiInstellingen> at src/views/settings/analytics.vue
<Anonymous>
<CWrapper>
<TheContainer> at src/containers/TheContainer.vue
<App> at src/App.vue
<Root>
I have seen many similar issues on the internet, and I know that it has to do with the fact that I try to access the data before it has rendered. None of the solutions that I found seemed to help me.
Here my code:
<template>
<div>
<p> {{allAnalytics[0].id}} </p>
</div>
</template>
<script>
import { mapGetters, mapActions } from "vuex";
export default {
name: "apiInstellingen",
methods: {
...mapActions(['fetchAnalytics'])
},
created() {
this.fetchAnalytics();
},
computed: mapGetters(['allAnalytics']),
};
</script>
Does anyone know a solution that would work in my case? I tried v-if, declaring in state, declaring the variable in data, but none of it seems to work...
Thank you!
Upvotes: 1
Views: 1585
Reputation: 1033
This is because your allAnalytics
array is undefined at the time you use it (fetching is not done yet), so you're not able to access the 0 index.
You could add render condition like this
<template>
<div>
<p v-if"allAnalytics && allAnalytics[0]"> {{allAnalytics[0].id}} </p>
</div>
Upvotes: 1
Reputation: 2421
What we can glean from the error message is that your allAnalytics
array is instantiated when the template renders, but it does not have any contents.
I think if you put v-if="allAnalytics.length > 0
on the parent div in the template, you won't see this error. But more importantly, you should ask yourself "Should this allAnalytics
array ever be zero-length?"
Perhaps you need to add a v-for
directive to the child <p>
tag to iterate the allAnalytics
array, something like the following. Of course, this depends on your use case.
<template>
<div>
<p v-for="item in allAnalytics" :key="item.id" > {{item.id}} </p>
</div>
</template>
Upvotes: 1