Using VueJS Computed Property along with Lodash Debounce

I have been encountering a slowdown while filtering through a large array of items based on user input. I decided to implement Lodash debounce to address this issue, but unfortunately, it doesn't seem to be having any effect.

Below is the HTML search input field where users can type to filter through the array:

<input v-model="search" type="text"/>

Here, I am iterating through the filteredIcons computed property to display the items:

<section v-if="icons.length">
  <button v-for="(icon, index) in filteredIcons" :key="index">
    <span v-html="icon.icon"></span>
    <span v-text="icon.name"></span>
  </button>
</section>

And here is the section where the large icons array is filtered through the computed property:

import { debounce } from "lodash";

export default {
  data() {
    return {
      icons: [
               {
                 "author":"svg",
                 "icon":"<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\"><path d=\"M13 16v5a1 1 0 01-1 1H9l-3-6a2 2 0 01-2-2 2 2 0 01-2-2v-2c0-1.1.9-2 2-2 0-1.1.9-2 2-2h7.59l4-4H20a2 2 0 012 2v14a2 2 0 01-2 2h-2.41l-4-4H13zm0-2h1.41l4 4H20V4h-1.59l-4 4H13v6zm-2 0V8H6v2H4v2h2v2h5zm0 2H8.24l2 4H11v-4z\"/></svg>",
                 "name":"icon-announcement.svg"
               },
               {
                 "author":"svg",
                 "icon":"<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\"><path d=\"M20 9v10a2 2 0 01-2 2H6a2 2 0 01-2-2V9a2 2 0 01-2-2V5c0-1.1.9-2 2-2h16a2 2 0 012 2v2a2 2 0 01-2 2zm0-2V5H4v2h16zM6 9v10h12V9H6zm4 2h4a1 1 0 010 2h-4a1 1 0 010-2z\"/></svg>",
                 "name":"icon-archive.svg"
               }
             ],
      search: ""
    };
  },
  computed: {
    filteredIcons: {
      get() {
        return this.icons;
      },
      set: debounce(function() {
        this.icons = this.icons.filter(icon => {
          icon.name.toLowerCase().includes(this.search.toLowerCase());
        });
      }, 500)
    }
  }
}

I'm puzzled by why this implementation isn't working as expected and would greatly appreciate any suggestions on the best approach for efficiently filtering through a large array using debounce. Thank you for your help!

Answer №1

It appears that your filter function is not properly returning the result of String#includes. As a result, all items are not matching the filter criteria, leading to an empty array. To fix this, you have two options:

const filteredIcons = this.icons.filter(icon => {
  return icon.name.toLowerCase().includes(this.search.toLowerCase())
})

You could add a return keyword in the code block or simply remove the brackets and semicolon:

const filteredIcons = this.icons.filter(icon => icon.name.toLowerCase().includes(this.search.toLowerCase()))

Furthermore, it is recommended to implement debounce functionality on user input rather than on the computed setter. One way to achieve this is by using a watcher on the input's v-model (i.e.,

search</code) and debouncing the result:</p>
<pre class="lang-js"><code>export default {
  watch: {
    search: {
      handler(search) {
        this.setIconsDebounced(search)
      },
      immediate: true
    }
  },
  methods: {
    setIconsDebounced: _.debounce(function(search) {
      this.filteredIcons = this.icons.filter(/*...*/)
    }, 500)
  }
}

This approach removes the need for the computed prop but requires declaring a variable to store the filtered icons in your data props:

export default {
  data() {
    return {
      filteredIcons: []
    }
  }
}

For a working demonstration, you can check out this demo.

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

Utilize AJAX to dynamically insert data into the database

I have created a JSP page that displays records, and now I am looking to include a dynamic link or button in the JSP that allows inserting data into the database without needing to refresh the page. This link should open a pop-up window with input fields ...

Allowing Angular2 Components and their Sub Components to access a shared instance of ngModel within a service

Currently, I have been working on constructing a complex view that requires multiple functionalities. To ensure proper organization, I have divided it into various custom components. I don't want to go into great detail, but I have managed to make it ...

Generate available choices for an asp:DropDownList using JavaScript without relying on the client-side ID

Can options be populated in an asp:DropDownList using JavaScript without the need for getElementById? I prefer a selector that utilizes classes. Appreciate any assistance. Goodbye. ...

Automated logout feature will be enabled if no user interaction is detected, prompting a notification dialog box

Here is my working script that I found on this site. After a period of idle time, an alert message will pop up and direct the user to a specific page. However, instead of just the alert message, I would like to implement a dialog box where the user can ch ...

Obtain the values from this JSON array

o = { "photos": { "page": 1, "pages": 46, "perpage": 5, "total": "230", "photo": [{ "id": "6643924777", "owner": "34653895@N08", "secret": "3b7c2f6469", "server": " ...

The saving function of the Jquery camera is not working properly and does not store the

I seem to be having an issue when using the jquery camera in "save" mode. Despite trying to call the url in "webcam.save" manually, it doesn't seem to have any effect. It appears that the jquery camera plugin may not be functioning as intended. Any su ...

Tips on incorporating the wait function within the evaluation_now action in Nightmare?

While I am incorporating Nightmare actions in my script, a question arises regarding the use of the wait function within the evaluate_now function. How can I utilize the wait function within the evaluate_now function? I am aware that I can simply use the ...

Executing intricate MongoDB collection queries using Node.js

I have a vast collection of records stored in MongoDB structured like the following example: { "key" : "a" ,"data" : "value1" , "lastname" : "Doe" }<br> { "key" : "ab" , "data" : "value1" , "lastname" : "Doe" }<br> { "key" : "abc" , "data" : ...

Incorporating URL addresses and pagination features using React.Js and Material-UI components

I have a functional component-page on my website, where I display a table that fetches data from an API. To improve user experience, I implemented pagination using the Material-UI library. While the pagination functionality works fine in updating the table ...

What is the method for initiating a radial gradient from the middle of the pie chart?

In my pie chart with grid lines, I have successfully implemented a radial gradient. However, the issue is that there is a separate gradient for each pie slice. What I really want is a single gradient originating from the center of the entire pie chart. I ...

Can the color scheme be customized for both light and dark themes in Ant Design version 5?

After creating a hook that successfully toggles between light and dark modes in Chrome's Rendering panel, I noticed that the values in the ConfigProvider remain unchanged when switching themes. Can anyone suggest a workaround to modify the design toke ...

Hover and hover-off functions in navigation menu

html <div class="hidden-nav"> <h4>lorem</h4> <ul class="decor-menu-list"> <li><a href="#">123</a></li> <li><a href="#">123</a></li> <li><a hre ...

Begin the React counter with a starting value of two

Recently, I set up a new React application using the create-react-app command and ran a test with a render counter. Here is the code snippet: import React, { useState } from "react"; let render = 0; export default function App() { const [cou ...

Incorporating a feature to leave comments in JSON data through AngularJS

Yesterday, I completed an AngularJS test that presented me with two tasks. One task involved displaying the data of a JSON file on a webpage in HTML form. I accessed the FreshlyPressed JSON via the link "" and effectively showcased the thumbnail, pos ...

What is the best way to choose an item from a list nested inside a div?

Currently, I am facing the challenge of selecting an item from a list that is structured using a div For this task, I am utilizing WebDriver IO () <div class="selectize-dropdown demo-default select-class single" style="display: none; width: 196px; top ...

The deployed vue.js application encounters a 404 error when the page is refreshed within the vue-router

While the homepage/base URL of the app can be refreshed with no problem, other pages return a 404 error when refreshed. Are there any workarounds for this issue? Take a look at this screenshot of the 404 error: [1]: https://i.sstatic.net/lc8xD.png ...

Problem with React Router: Uncaught Error - Invariant Violation: The element type is not valid, a string is expected for built-in components

I am encountering an issue with react-router and unable to render my app due to this error. Here is a screenshot of the error I have searched extensively for a solution but have not been able to find anything useful. Any help would be greatly appreciated ...

How can I integrate the native calendar of an Android device in Phonegap?

What is the best way to add an event to an Android device's calendar using phonegap? I need to make sure it works on Android Version 2.3 and above. The available plugins are not functioning correctly, so I am looking for alternative solutions. ...

What could be causing my select value to stay unchanged? Issue with the "selected" attribute or property

var original_role = $('option:selected', '#user_role').val(); $('#role_cancel').click(function() { //console.log(original_role); $('option:selected', '#user_role').removeAttr('selected'); //des ...

I am interested in creating JSON data

Below is the provided json data: { "id": 0, "isLeaf": false, "name": "root", "children": [ { "id": 3, "isLeaf": false, "name": "Node 2", "pid": 0, "disabled": true }, { "id": "new5", "isLeaf": ...