Why is refresh Apex not working during Inline Edit? When I edit the record, even though the new value gets updated, but in the datatable the old value gets displayed. How can I fix this?
.html
<template>
<lightning-card>
<div class="slds-m-top_medium slds-m-bottom_x-large">
<div class="slds-p-around_medium lgc-bg">
<lightning-input type="text" label="Search box" placeholder="type here..." value={searchValue} onchange={searchKeyword}></lightning-input>
</div>
<lightning-button variant="brand" label="Search" title="Search" onclick={handleClick} class="slds-m-left_x-small"></lightning-button>
</div>
<div class='slds-m-around_medium'>
<lightning-datatable
key-field='Id'
data={records}
columns={columns}
hide-checkbox-column
draft-values={draftValues}
onsave={handleSave}>
</lightning-datatable>
</div>
</lightning-card>
</template>
.js
export default class Sample extends LightningElement {
records;
error;
draftValues = [];
searchValue = '';
searchKeyword(event){
this.searchValue = event.target.value;
}
handleClick(){
fetchAccounts({key: this.searchValue})
.then(result => {
this.records = result;
})
.catch( error=>{
this.records = null;
});
}
async handleSave( event ) {
const updatedFields = event.detail.draftValues;
const notifyChangeIds = updatedFields.map(row => { return { "recordId": row.Id } });
await updateAccounts( { data: updatedFields } )
.then( result => {
console.log( JSON.stringify( 'Apex update result: ' + result ) );
getRecordNotifyChange(notifyChangeIds);
refreshApex( this.records).then( () => {
this.draftValues = [];
});
}).catch( error => {
console.log( 'Error is ' + JSON.stringify( error ) );
});
}
}
Apex
public with sharing class AccountController {
@AuraEnabled( cacheable = true )
public static List< Account > fetchAccounts(String key) {
return [ SELECT Name FROM Account WHERE Name = :key ];
}
@AuraEnabled
public static string updateAccounts( Object data ) {
List < Account > accsForUpdate = ( List < Opportunity > ) JSON.deserialize(
JSON.serialize( data ),
List < Account >.class
);
try {
update accsForUpdate;
return 'Success: Account(s) updated successfully';
}
catch (Exception e) {
return 'The following exception has occurred: ' + e.getMessage();
}
}
}