Clinton Green
Clinton Green

Reputation: 9977

Vue syntax error

I am trying to print out the name property of an object using Vue.

Here's what I tried {{ selectedTopic.name }}, this throws this error Uncaught TypeError: Cannot read property 'name' of null

If I print out {{ selectedTopic }} it will wait until that data is available and then display without errors.

Now I understand that the data I'm requesting is not available at that stage, but why is it throwing an error? Shouldn't it just wait until that data becomes available like it does for {{ selectedTopic }}?

Vue app

  var qaSuggest = new Vue({
    el: '#qa-suggest',
    data: {
      selectedTopic: null,
      profiles: []
    },
    mounted() {
      bus.$on("send-topic", selectedTopic => this.selectedTopic = selectedTopic);
    },
    updated(){
      axios.get('/vueprofiles').then(response => this.profiles = response.data);
      console.log('selectedTopic: ', this.selectedTopic.name);
    }
  });

HTML

<div id="qa-suggest">
    <ul class="list-unstyled">
        <li v-for="profile in profiles">
          <div class="clearfix" style="border-bottom: 1px solid #ddd; padding: 5px;">
        <div class="pull-left">
          <img :src="profile.picture" class="img-responsive" style="max-width: 60px; margin-right: 10px;">
        </div>
        <div class="pull-left">
          <p style="font-size: 12px; margin-bottom: 0;">{{ profile.category }} / {{ profile.subcategory }}</p>
          <p><strong>{{ profile.name }}</strong></p>
        </div>
      </div>
    </li>
</ul>

Topic: {{ selectedTopic.name }}

Upvotes: 1

Views: 1168

Answers (3)

Bert
Bert

Reputation: 82489

The error is because you can't access a property on an object that is null. Instead, you might try

{{ selectedTopic ? selectedTopic.name : '' }}

Upvotes: 1

Decade Moon
Decade Moon

Reputation: 34306

You'll get the same kind of error if that were put into a computed property. Vue just executes the JS code as-is without any kind of null-protection.

In your case, I would protect that part of the template with a v-if="selectedTopic", or just use null checking directly in the interpolation: {{ selectedTopic ? selectedTopic.name : 'No topic selected' }}.

You could also initialize it to a default value, like an empty object {}, but in my opinion this is flawed because selectedTopic is now non-null but in fact no actual topic is selected, which complicates the code.

Upvotes: 1

Roy J
Roy J

Reputation: 43899

It doesn't "wait" so much as understand that undefined should be an empty string. You could initialize selectedTopic with an empty object, and you would get the result you're looking for.

data: {
  selectedTopic: {},
  profiles: []
},

Upvotes: 1

Related Questions