LWC Wire Service – Troubleshooting No Results Issue

I'm brand new to LWC (and components in general). I've been doing an online course and through that, I've built a simple component which has user input to search for a Lead. That's working okay, but the issue is whenever the initial search is amended (adding or removing characters), the change event handler fires but the wire service doesn't provision any new data. This results in this.leads being undefined for every search after the first one.

I'm not sure if it's because the wire service not attempting to search or if it's because some parameter is undefined and preventing it from doing so. Either way, I don't know how to debug it nor ultimately how to fix it.

Markup:

<template>
    <lightning-card  title="Lead Search" icon-name="standard:search" class="slds-m-around_medium">
        <div class="slds-box slds-theme_default">
            <lightning-input
                    label="Search Term"
                    variant="label-hidden"
                    placeholder="Search by name, phone, website, or address"
                    type="text"
                    value={searchTerm}
                    onchange={handleSearchTermChange}>
            </lightning-input>
        </div>
    </lightning-card>
</template>

Javascript:

import { LightningElement, track, wire} from 'lwc';
import searchLeads from '@salesforce/apex/LeadSearchController.searchLeads';

const DELAY = 1000;

export default class LeadList extends LightningElement {
    @track leads = [];
    @track searchTerm;
    @track error;

    handleSearchTermChange(event) {
        if(this.leads) {
            this.searchTerm = event.target.value;
            const selectedEvent = new CustomEvent('newsearch', {detail: this.searchTerm});
            window.clearTimeout(this.delayTimeout);
            this.delayTimeout = setTimeout(() => {
                this.dispatchEvent(selectedEvent);
            }, DELAY);
        }
    }

    @wire(searchLeads, {
        searchTerm: '$searchTerm'
    })
    loadLeads({error, data}) {
        if(data) {
            this.leads = data;
            const selectedEvent = new CustomEvent('searchcomplete', {
                detail: this.searchTerm
            });
            this.dispatchEvent(selectedEvent);
            this.error = undefined;
        }
        else if(error) {
            this.error = error;
            this.leads = undefined;
        }
    }
}

Best Answer

Your problem may relate to how handleSearchTermChange only processes the change if this.leads is truthy. If an error happens the change to search term won't recover because you set this.leads to undefined (falsy).

Related Topic