Search code examples
vue.jserror-handlingconsolevuextypeerror

[Vue warn]: Error in render: "TypeError: Cannot read property 'xxx' of undefined"


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!


Solution

  • 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>