I am trying to build a lighting web component which uses lightning datatable with Server side search capabilities.
here is the code: I am not sure what I am doing wrong.
.HTML
<template>
<div class="slds-m-around_medium">
<lightning-input type = "search" value={searchKey} onchange={handleKeywordChange}>
</lightning-input>
</div>
<template if:false={Acc} >
<lightning-datatable
data={Acc}
columns={columns}
hide-checkbox-column="true"
hide-row-number-column="true"
key-field="id" >
</lightning-datatable>
</template>
.JS
import { LightningElement, wire, track, api } from 'lwc';
import Id from '@salesforce/user/Id';
import fetchAccounts from '@salesforce/apex/ManageAccounts.fetchAccounts'
const columns = [
{
label: 'Account ID',
fieldName: 'ID',
editable: true
}, {
label: 'Account Name',
fieldName: 'Name',
editable: true
}, {
label: 'Account Number',
fieldName: 'AccountNumber',
editable: true
}, {
label: 'Account Type',
fieldName: 'Type',
editable: true
}
];
export default class ManageAccount extends LightningElement {
userId = Id;
@track searchKey;
@track columns = columns;
@track Acc;
@track error;
renderedCallback(){
if(this.isSearchChangeExecuted){
return;
}
fetchAccounts({
userId: this.userId,
searchKey: this.searchKey
})
.then( response => {
this.Acc = response;
this.error = undefined;
})
.catch (e => {
this.error = e;
this.Acc = undefined;
})
}
handleKeywordChange(event){
this.isSearchChangeExecuted = false;
this.searchKey = event.target.value;
}
}
.controller
public with sharing class ManageAccounts {
@AuraEnabled (cacheable=true)
public static List<Account> fetchAccounts( string userId, string searchKey){
List <Account> acclist = new List<Account>();
string strgkeyword = '%'+searchKey+'%';
string query = 'SELECT Id, Name, AccountNumber, Type FROM Account WHERE OwnerId=: userId' ;
if(!String.isEmpty(searchKey)){
query += ' AND Name LIKE \'%'+searchKey+'%\';
}
acclist = Database.query(query);
return acclist;
}
}
- Updated the dynamic query on the controller file based on input from @sfdcfox which was one of the issue.
Best Answer
Onchange might not be fired until the input is blurred (lost focus). This is really browser-dependent behavior. You might want to just use onkeyup with a small delay: