2

The data is on firebase, and I want to show only 1 object with [objectNumber] see {{ligler[1].name}} in the template, but when I do this it works but I get errors:

  • Error when rendering component
  • Uncaught TypeError: Cannot read property 'name' of undefined

I think, the problem is that the data loaded before the component.

When I use v-for, it show the name off all objects without errors, but I only want to show one object.

The template looks like:

<template>
  <div id="app">
  <h1>{{ligler[1].name}}</h1>
  </div>
</template>

the script:

<script>
import Firebase from 'firebase'

let config = {
    apiKey: "xxxxxxxxxx",
    authDomain: "xxxxxxxxxx",
    databaseURL: "https://xxxxxxxxxx.firebaseio.com"
}

let app = Firebase.initializeApp(config);
let db = app.database();

let ligRef = db.ref('ligler');

export default {
  name: 'app',
  firebase: {
    ligler: ligRef
  }
}
</script>

I tried to add v-if to the h1, but that doesn't work.

How can I fix this errors?

Can
  • 553
  • 1
  • 9
  • 29

2 Answers2

2

Put a null check like this:

<h1>{{ligler[1] && ligler[1].name}}</h1>

Using && or || are called logical operator short circuiting meaning they don't evaluate the right hand side if it isn't necessary. This is widely used due to it's brevity.

Here if ligler[1] is undefined, it will not evaluate ligler[1].name and you will not be getting the error, which is equivalent of putting a if before accessing the inside properties.

It makes more sense to use v-if if you have more component where you access other properties of ligler[1] as well, otherwise above code is better.

  <div v-if="ligler[1]">
    <h1>{{ligler[1].name}}</h1>
    <h1>{{ligler[1].age}}</h1>
    <h1>{{ligler[1].etc}}</h1>
  </div>
Community
  • 1
  • 1
Saurabh
  • 71,488
  • 40
  • 181
  • 244
  • this works!!!! can you explain why I must add ligler[1] &&? Just to identify ligler? – Can Jan 20 '17 at 08:37
  • thanks!!! v-if="ligler[1]" is also working, which one is better to use? – Can Jan 20 '17 at 08:43
  • @Saurahbh, I have one question more.. in my data I have ligler[1].currentWeek and ligler[1].weeks how can I set currentWeek as variable to use this to show the current week in ligler[1].weeks? – Can Jan 20 '17 at 08:59
1

Usually you can simplify this by using v-if:

<template>
  <div id="app" v-if="ligler[1]">
    <h1>{{ligler[1].name}}</h1>
  </div>
</template>
str
  • 42,689
  • 17
  • 109
  • 127
  • this works! is this solution better then

    {{ligler[1] && ligler[1].name}}

    ?
    – Can Jan 20 '17 at 08:40
  • @Can It depends. If the whole component depends on `ligler[1]` then use `v-if`, if it is only a small part of the component use `&&`. – str Jan 20 '17 at 08:46