Vuejs template : "Cannot read properties of null" but Array is defined

58 views Asked by At

I want to display an array elements in my Vuejs template.

I am getting data from API, formatting them into an associative Array with a function and then trying to display in the template :

export default {
  components: {
    DefaultHeader,
    DefaultFooter
  },
  data() {
    return {
      info: null,
    };
  },
  mounted() {
    this.refreshData();
  },
  methods: {
    refreshData() {
      infoService.getInfo(this.$route.params.id)
        .then(response => {
          this.info = FormatHelper.BInfoFormat(response.data);
        })
        .catch(e => {
          console.log(e);
        });
    }
  }
}

When i try to display the first element in the template with this code :

{{ this.info.name }}

I get the error :

Uncaught (in promise) TypeError: Cannot read properties of null (reading 'name')

But when I display the full Array Object at the exact same place in code, I can see that it's defined :

{{ this.info }}

shows :

{ "name": "B3", "call": "about", "G": "H" }

Also, I get the right data when i try to console log in my mounted() component function :

console.log(this.info.name)

What is wrong in the way I am trying to access data getting me this error ?

1

There are 1 answers

2
Jean-Loup On BEST ANSWER

Problem solved, thanks to comments :

in :

export default {
  components: {
    DefaultHeader,
    DefaultFooter
  },
  data() {
    return {
      info: null,
    };
  },
  mounted() {
    this.refreshData();
  },
  methods: {
    refreshData() {
      infoService.getInfo(this.$route.params.id)
        .then(response => {
          this.info = FormatHelper.BInfoFormat(response.data);
        })
        .catch(e => {
          console.log(e);
        });
    }
  }
}

replace :

  data() {
    return {
      info: null,
    };
  },

by :

  data() {
    return {
      info: {},
    };
  },

The initial define at null is breaking the Array methods I was trying to use in the template.