Trouble with controlling the speed of ajax requests while using vue-multiselect and lodash

I am working on a Vue application that includes a vue-multiselect component. My goal is to load the multiselect options via ajax. To achieve this, I am using lodash.throttle to limit the frequency of ajax requests as the user types in the search criteria. However, I am encountering an issue where multiple requests are being sent for each character entered in the search field. Can someone help me identify what I might be doing wrong? Appreciate any assistance in advance.

<template>
<multiselect :options="allLocations.map(p => p.externalId)" 
                :searchable="true" 
                :custom-label="uuid => {const sel = allLocations.filter(s => s.externalId === uuid); return sel.length === 1 ? sel[0].name + ' (' + sel[0].type + ')' : '';}" 
                class="mx-1 my-1" 
                style="width:500px;" 
                v-model="locations"
                :clear-on-select="true" 
                :close-on-select="false" 
                :show-labels="true" 
                placeholder="Pick Locations to filter" 
                :multiple="true" 
                :loading="locationsLoading" 
                :internal-search="false"
                @search-change="findLocations"
                @input="updateLocations" 
                :allowEmpty="true" />
</template>
<script>
import {throttle} from 'lodash'
export default {
name: 'test-throttle-component',
data() {
allLocations: [],
locationsLoading: false,
locations: [],
},
methods: {
findLocations(search) {
      this.$log.debug("Going to find locations for search criteria", search)
      const params = {search: search}
      this.locationsLoading = true
      const self = this
      throttle(() => self.$http.get("locations/ddlist", {params}).then(res => {
        self.allLocations = res.data.items
        self.locationsLoading = false
      }), 5000)()
    },
updateLocations() {
      const self = this
      this.$store.dispatch('updateSelectedLocations', this.locations)
        .then(() => self.emitRefresh())
    },
}
}
</script>

Answer №1

While @strelok2010's response was on the right track, it seems that he missed the fact that the vue multiselect @search-change handler requires a function that takes the search argument. This means that the code provided will not work as expected. Additionally, the arrow function may not properly reference the component, so using a standard JS function might be necessary. Here is an alternative solution:

findLocations: throttle(function(search) {
      this.$log.debug("Finding locations based on search criteria", search)
      const params = {search: search}
      const self = this
      this.locationsLoading = true
      self.$http.get("locations/ddlist", {params}).then(res => {
        self.allLocations = res.data.items
        self.locationsLoading = false
      }
}, 5000)

Answer №2

One way to enhance the performance of the findLocations method is by encapsulating it within the throttle function:

findLocations: throttle(() => {
      this.$log.debug("Going to find locations for search criteria", search)
      const params = {search: search}
      const self = this
      this.locationsLoading = true
      self.$http.get("locations/ddlist", {params}).then(res => {
        self.allLocations = res.data.items
        self.locationsLoading = false
      }
}, 5000)

For further details, check out this resource

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Navigating through the DOM using JavaScript or regular expressions

I have a DOM string called innerHTML and I am looking to extract or display the node value using either JavaScript's DOM API or JavaScript RegEx. "<nobr> <label class="datatable-header-sortable-child" onmousedown="javascript:giveFeedback(&ap ...

Using Ajax to submit two forms by clicking a submit button

Explanation : In this particular scenario, I am facing a challenge where I need to trigger another Ajax function upon successful data retrieval, but unfortunately, I am encountering some unknown obstacles. Code: ---HTML Form : <form accept-charset=" ...

Ajax redirection with Symfony

The login page utilizes ajax, with the controller responding in the web browser view as {"response":true,"data":{"from":"apachecms_api_login_submit","to":"/dashboard"}} without redirecting. When successful, the function triggers an ajax call. functio ...

What are some effective strategies for incorporating AJAX into DataGrids?

After reading various blogs, I came across a recommendation to minimize the use of Update Panels. In my scenario involving a Data Grid and an Update Panel, what would be the most effective approach? 1) Should I keep the Data Grid inside the Update Panel? ...

Could someone clarify why EventEmitter leads to issues with global variables?

I recently encountered an error that took me some time to troubleshoot. Initially, I decided to create a subclass of EventEmitter In the file Client.js var bindToProcess = function(func) { if (func && process.domain) { return process.domai ...

Exploring Alternative Methods for Serving Static HTML Files in an Express Server

Hey there, quick question for you. Let's say I have two static HTML files that I want to serve in Express - 'index.html' and 'contact.html'. I've been playing around with some basic Express code to get them served: const expr ...

Navigating and exploring data stored in a mongoose database

Currently, I am attempting to filter data based on a specific id (bWYqm6-Oo) and dates between 2019-09-19 and 2019-09-22. The desired result should return the first three items from the database. However, my current query is returning an empty array. I wou ...

Update the network name in the Axios request

Currently, I am utilizing Axios for handling both GET and POST requests. One question that has been on my mind is how to modify the network name: At present, the name serves as the parameter accompanying each request. However, I ponder whether it's f ...

modify the name attribute of a select dropdown using jQuery dynamically

In my current project, I am working on dynamically changing the "name" attribute for each select box based on user interactions. The scenario is as follows: When a user clicks on an option in the first select box, a new select box appears with the remainin ...

typescriptCreating a custom useFetch hook with TypeScript and Axios

I have a query regarding the utilization of the useFetch hook with TypeScript and Axios. I came across an example of the useFetch hook in JavaScript, but I need help adapting it for TypeScript. The JavaScript implementation only handles response and error ...

Adding text after a div in React-JS using Bootstrap: A quick guide

Just starting out with website development and I have a question. As I practice making this website, I am struggling to figure out how to add the text "To know more about us click here" below the 'Get started' button. I tried adding a simple < ...

How to prevent VueJS observer from monitoring a temporary variable

My VueJS and Observer objects are causing me trouble. I am encountering an issue where I assign a part of my object to a temporary variable for later use, update the original part with new data, and then revert it back to its original state after 8 seconds ...

Is there a way to replicate the ctrl-F5 function using jQuery?

Is there a way to use jQuery to refresh the page and clear the cache at the same time? ...

In search of a highly efficient webservices tutorial that provides comprehensive instructions, yielding successful outcomes

I've reached a point of extreme frustration where I just want to break things, metaphorically speaking, of course. For the past week, I've been trying to learn how to create a web service using C# (whether it's WCF or ASMX, I don't rea ...

Tips for preventing the error message "The property 'map' is not present on type 'string | string[]'."

I received an error message stating Property 'map' does not exist on type 'string | string[]': const data = [ ['1', ['11']], ['2', ['21']], ['3', ['31']], ] data.map(top ...

React-redux: Data of the user is not being stored in redux post-login

Hello everyone, I am fairly new to using react-redux and I'm currently facing an issue with storing user information in the redux store after a user logs in. I am utilizing a django backend for this purpose. When I console out the user in app.js, it ...

I am attempting to change a "+" symbol to a "-" symbol using a Bootstrap toggle feature

Click on the text to reveal more information that drops down below. I am using Bootstrap icons and attempting to show a "+" icon when the toggle is collapsed, and a "-" icon when it's open. I've been trying to use display properties, but haven&ap ...

Guide on excluding certain words within a paragraph using PHP

In my database, there is a paragraph that looks like this: $str ="this is a paragraph i show shortly and when i click on the view more it will show completely for that i am using the ajax and retrieve it " I display it as follows: this is a paragrap ...

Combining Flask and HTML: Passing a SQLite3 query result from Flask to HTML and utilizing Jinja2 for rendering

I am currently working on implementing a continuous loading feature for my webpage. With the help of JavaScript, I have successfully set it up to call a Python Flask function whenever the user reaches the bottom of the page in order to retrieve the next se ...

What is causing .attr('title') to retrieve the title of the element before?

UPDATE Flexslider now includes several callback spaces for use, making this functionality possible. after: function(){}, //Callback: function(slider) - Fires after each slider animation completes Thank you to everyone who contributed! LIVE CO ...