1

For some reason the this is undefined if I'm using a debounce function. I have tried to bind it but still it is undefined. I can't understand what is happening here..

For example here this is working and returns

VueComponent {_uid: 6, _isVue: true, $options: {…}, _renderProxy: Proxy, _self: VueComponent, …}

<template>
    <at-ta @at="fetchMembers">
        <textarea></textarea>
    </at-ta>  
</template>

fetchMembers(at)
{
    console.log(this) // <-- VueComponent { ...
},

But when I move it to a debounce function it isn't working anymore but is

this is undefined

fetchMembers: debounce(at => {
    axios.get(`/api/users?name=${at}`).then(({data}) => {
        this.members = data  // <-- this is undefined
    })
}, 500)
Martin Zeltin
  • 2,496
  • 3
  • 18
  • 36
  • Use a function expression instead of an arrow function. See [Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?](https://stackoverflow.com/q/34361379/218196). And then of course `debounce` must correctly "forward" the value of `this` to the wrapped function. – Felix Kling Sep 23 '20 at 10:56
  • Can you please show an example how? – Martin Zeltin Sep 23 '20 at 10:56
  • `fetchMembers: debounce(function(at) { ... }, 500)` – Felix Kling Sep 23 '20 at 10:57

1 Answers1

3

Don't bind the debounced function, but do bind the axios promise callback.

methods: {
  fetchMembers: debounce(function (at) {
    axios.get(`/api/users?name=${at}`).then(({data}) => {
      this.members = data
    })
  }, 500)
}

It didn't work for you because you used a fat arrow function for the debounced function where this is undefined at that scope.

Keep in mind that you're only creating one debounced function that will be shared across all instances of your component. If this is an issue, you can instead wrap fetchMembers with a debounced function in the created hook:

created() {
  this.fetchMembers = _.debounce(this.fetchMembers, 500)
},

methods: {
  fetchMembers() {
    axios.get(`/api/users?name=${at}`).then(({data}) => {
      this.members = data
    })
  }
},
Decade Moon
  • 32,968
  • 8
  • 81
  • 101