Search code examples
vue.jsvuextypeerror

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


The service data comes from mapGetters using vuex store. When I display the values I get the error

Error Screenshot

I get the error in console, but the data gets displayed anyway. Why does this happen? How can I remove the error

<table border="0" id="tab">
             <tr><td >Name </td><td >: {{services[0].organization.name}}</td></tr>
             <tr><td>Name of Organisation </td><td>: {{services[0].organization.organizationName}}</td></tr>
             <tr><td>Email </td><td>: {{services[0].organization.email}}</td></tr>
             <tr><td>Mobile </td><td>: {{services[0].organization.phone}}</td></tr>
             <tr><td>Location </td><td>: {{services[0].organization.address.no}} {{services[0].organization.address.street}} {{services[0].organization.address.locality}} {{services[0].organization.address.state}}</td></tr>
             <tr><td>Zipcode </td><td>: {{services[0].zipcode}}</td></tr>
</table>

Solution

  • Very straight forward and simple solution would be to hide table until services[0] will be available:

    <table border="0" id="tab" v-if="services[0]">
    

    I suppose the initial state or services is empty array that's why when the first component render occurs it shows these errors because services[0].organization cannot be accessed at this very moment.

    Going further you can define computed prop that will return organization object with some default values if if don't wish to hide a table at all.

    <tr><td >Name </td><td >: {{organization.name}}</td></tr>
    
      computed: {
         organization () {
           if (!this.services[0]) {
              return {
                name: '',
                //  other organization props here
              }
           }
           return this.services[0].organization
         }
      }