0

I'm building a little vue.js-application where I do some post requests. I use the watch-method to whach for api changes which then updates the component if the post request is successfull. Since the watcher constantly checks the API I want to add the ._debounce method but for some reason it doesn't work.

here is the code:

<script>
import _ from 'lodash'
export default { 
    data () {
      return {
        cds: [],
        cdCount: ''
     }
   },
   watch: {
     cds() {
       this.fetchAll()
     }
   },
   methods: {
      fetchAll: _.debounce(() => {
        this.$http.get('/api/cds')
         .then(response => {

          this.cds = response.body
          this.cdCount = response.body.length
         })
     })
  },
  created() {
     this.fetchAll();
  }
}
</script>

this gives me the error: Cannot read property 'get' of undefined

Can someone maybe tell me what I'm doing wrong?

EDIT

I removed the watch-method and tried to add

updated(): {
  this.fetchAll()
}

with the result that the request runs in a loop :-/ When I remove the updated-lifecycle, the component does (of course) not react to api/array changes... I'm pretty clueless

ST80
  • 3,565
  • 16
  • 64
  • 124

1 Answers1

3

Mind the this: () => { in methods make the this reference window and not the Vue instance.

Declare using a regular function:

   methods: {
      fetchAll: _.debounce(function () {
        this.$http.get('/api/cds/add').then(response => {
          this.cds = response.body
          this.cdCount = response.body.length
         })
     })
   },

Other problems

You have a cyclic dependency.

The fetchAll method is mutating the cds property (line this.cds = response.body) and the cds() watch is calling this.fetchAll(). As you can see, this leads to an infinite loop.

Solution: Stop the cycle by removing the fetchAll call from the watcher:

  watch: {
    cds() {
     // this.fetchAll() // remove this
    }
  },
acdcjunior
  • 132,397
  • 37
  • 331
  • 304