vuejs / vuefire

🔥 Firebase bindings for Vue.js
https://vuefire.vuejs.org
MIT License
3.86k stars 333 forks source link

TypeError: Cannot read property 'val' of undefined #210

Closed crholliday closed 6 years ago

crholliday commented 6 years ago

I have been grinding on this for a bit. The good news: everything works. The bad news: the error is still there! This error occurs when I navigate via a router-link to another location then come back via a router.push().

The error I am getting is not helpful to me:

TypeError: Cannot read property 'val' of undefined
    at VueComponent.clicksVal (Home.vue?76f2:55)
    at Watcher.get (vue.runtime.esm.js?2b0e:3138)
    at Watcher.evaluate (vue.runtime.esm.js?2b0e:3245)
    at VueComponent.computedGetter [as clicksVal] (vue.runtime.esm.js?2b0e:3503)
    at Object.get (vue.runtime.esm.js?2b0e:1916)
    at Proxy.render (eval at ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules\\.cache\\vue-loader","cacheIdentifier":"46ed2be8-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/pug-plain-loader/index.js!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./src/views/Home.vue?vue&type=template&id=fae5bece&scoped=true&lang=pug& (app.js:1085), <anonymous>:52:56)
    at VueComponent.Vue._render (vue.runtime.esm.js?2b0e:4540)
    at VueComponent.updateComponent (vue.runtime.esm.js?2b0e:2784)
    at Watcher.get (vue.runtime.esm.js?2b0e:3138)
    at new Watcher (vue.runtime.esm.js?2b0e:3127)

The offending bit of code is here (note that 'val' is a property in my data and it is only called in the line below I have an arrow showing):

computed: {
    role() {
      return this.$store.state.role
    },
    ...mapGetters({
      streamCode: 'getStreamCode'
    }),
    clicksVal() {
      try {
        return this.clicks[this.streamCode].val  // <--- this is where the error originates
      } catch (err) {
        console.log(err)
      }      
    }
  },
  firebase: function () {
    return {
      clicks: {
        source: db.ref('clickStream'),
        asObject: true
      }
    }
  },

That computed value is called in my template like this:

<template lang="pug">
  .home
    .need-key(v-if='!streamCode')
      input(type='text' v-model='newKey' placeholder='Enter a code')
      button.get(@click.prevent='login') Get clicks!
    .have-key(v-else)
      h1(v-if='clicks') {{ clicksVal }}
      h4(@click.prevent='startOver') {{ streamCode }}
      ...
</template>
posva commented 6 years ago

Hey, this is probably because clicks is empty at the beginning, you should add some kind of guard in your clicksVal like this.clicks[a] && this.clicks[a].val