[Vuejs]-VueJS cannot read property 'name' of undefined causing UI error

0๐Ÿ‘

โœ…

<template v-if='api && api.info.hasOwnProperty("name")'>
    <strong>Developer:</strong> {{api.info.contact.name || api._meta.github_username }}<br>
</template>

hasOwnProperty ended up working finally

0๐Ÿ‘

You could create Proxy which will return empty object {} when property is undefined. Something like Elvis opertor in TypeScript.

function safe(obj) {
  return new Proxy(obj, {
    get: function(target, name) {
      const result = target[name];
      if (!!result) {
        return (result instanceof Object)? safe(result) : result;
      }
      return safe({});
    }
  });
}

Usage example:

const jane = {
  name: 'Jane',
  age: 35
};

const john = {
  name: 'John',
  address: {
    street: '7th Avenue',
    city: 'Ecmaville',
    zipCode: '23233'
  },
  sister: jane,
  age: 28
};
var sjohn = safe(john);                    
console.log(sjohn.name);                  // --> "John"
console.log(sjohn.address.street);        // --> "7th Avenue"
console.log(sjohn.sister.name);           // --> "Jane"
console.log(sjohn.sister.address);        // --> {}
console.log(sjohn.sister.address.street); // --> {}

Leave a comment