Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throttle or debounce async calls in Vue 2 while passing arguments to debounced function

I have a Vue 2 application that uses an array of objects to back a search/multiselect widget provided by vue-multiselect.

I have looked at the Vue 1 -> 2 migration guide on debouncing calls, but the example they give did not propagate the arguments from the DOM elements to the business logic.

Right now the select fires change events with every keystroke, but I would like to throttle this (EG with lodash#throttle) so I'm not hitting my API every few milliseconds while they're typing.

import {mapGetters} from 'vuex';
import { throttle } from 'lodash';

import Multiselect from 'vue-multiselect'

export default {
  components: {
    Multiselect
  },
  data() {
    return {
      selectedWork: {},
      works: [],
      isLoading: false
    }
  },
  computed: {
    ...mapGetters(['worksList']),
  },
  methods: {
    getWorksAsync: throttle((term) => {
      // the plan is to replace this with an API call
      this.works = this.worksList.filter(work => titleMatches(work, term));
    }, 200)
  }
}

Problem: when the user types in the select box, I get the error:

TypeError: Cannot read property 'filter' of undefined

which is happening because this.worksList is undefined inside the throttle function.

Curiously, when I use the dev tools debugger, this.worksList has the value I need to dereference, with this referring to the Vue component.

Currently I am not calling the API from within the component, but the problem remains the same:

  1. How can I throttle this call, and have the proper this context to update my this.works list? EDIT: this is explained in Vue Watch doesnt Get triggered when using axios
  2. I also need to capture the user's query string from the multiselect widget to pass to the API call.

What is the proper pattern in Vue 2?

like image 887
Matt Morgan Avatar asked Nov 08 '22 08:11

Matt Morgan


1 Answers

I ran into the same issue when using lodash.debounce. I'm a huge fan of arrow syntax, but I discovered that it was causing _.throttle() and _.debounce(), etc. to fail.

Obviously my code differs from yours, but I have done the following and it works:

export default {
   ...,
   methods: {
     onClick: _.debounce(function() {
       this.$emit('activate', this.item)
     }, 500)
  }
}

Even though I'm not using arrow syntax here, this still references the component inside the debounced function.

In your code, it'd look like this:

export default {
  ...,
  methods: {
    getWorksAsync: throttle(function(term) {
      // the plan is to replace this with an API call
      this.works = this.worksList.filter(work => titleMatches(work, term));
    }, 200)
  }
}

Hope that helps!

like image 115
dzwillia Avatar answered Nov 09 '22 22:11

dzwillia