I had to build a custom lookup for my Lighting Competent. So it has a html input that you type in text and it does a search on each keyup showing the top 10 results below as a menu item. This allows the user to then click on menu item to select it for the lookup.

Is there a better way of doing this? Is this OK practice? It's searching an object with about 300-400 records if it matters.

My main concern is the fact I was doing a SOQL query every key-press.


The Lightning framework has a built-in rate-limiting system, so there may be some latency between key presses and when results are displayed. This may or may not be a significant problem, but at least from a technical perspective, it shouldn't cause any major issues. However, if you're only ever going to have a few hundred records, it might be better to just load all the records, possibly store them in a cache in localStorage (optional), and then do client-side filtering. I wrote an example in Aura, it would be pretty easy to translate to LWC.

|improve this answer|||||
  • In your example, filterHelper.js line 10 - looks like you're missing component.set() in order to set the new data there – Brian Miller Aug 29 '19 at 9:35
  • 1
    @BrianMiller My example has users manually adding rows as opposed to loading data from the server or such. It was made for another question some time ago, It was meant to demonstrate a basic concept without any metadata dependencies. The code definitely works, it's in my dev org somewhere. – sfdcfox Aug 29 '19 at 11:46
  • Thanks for the response I was more concerned if doing it this way was egregious or not. It doesn't seem like the case so I'm just going to leave it with how it is. – Halfwarr Aug 29 '19 at 14:25

You could consider using a "debouncing" method in Javascript. The idea of debouncing is that instead of directly attaching an expensive piece of code to a frequently called event handler (e.g. keypress, window-scroll, etc.), you attach a debounced version.

In the debounced version, the underlying function is called at most once every X milliseconds. So, in your case, if you configured debouncing for 300ms, it wouldn't fire the SOQL query on every press. If they were typing a lot, it would fire after 300ms of typing, then again when they stop.

I've done this in Aura by using the lodash library e.g. I had a helper function that I wanted to fire on window resize:

In the component:

<ltng:require scripts="{!$Resource.lodash_js}" afterScriptsLoaded="{!c.afterScriptsLoaded}" />

In the controller:

afterScriptsLoaded : function(component, event, helper) {
    const debouncedSetHeightInPx =
        _.debounce($A.getCallback(function() {
        }), 10);
    window.addEventListener('resize', debouncedSetHeightInPx);
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.