I had a LWC component which simply update an record. When logic was in one file it was working fine.
btn_newPhoneNumberClick() {
const fields = {};
fields.Id = this.recordId;
fields[LEAD_RTID.fieldApiName] = this.findRecordTypeId('Call');
fields[LEAD_PHONE.fieldApiName] = this.newPhoneNumber;
const recordInput = { fields };
updateRecordWithToast(recordInput);
}
// Require: import { ShowToastEvent } from 'lightning/platformShowToastEvent';
updateRecordWithToast(recordInput) {
updateRecord(recordInput)
.then(() => {
this.dispatchEvent(
new ShowToastEvent({
title: 'Success',
message: 'Lead updated',
variant: 'success'
})
);
// Display fresh data in the form
return refreshApex(this.lead);
})
.catch(error => {
this.dispatchEvent(
new ShowToastEvent({
title: 'Error updating record',
message: error.body.message + ' \nStatus: ' + error.statusText,
variant: 'error'
})
);
});
}
Now since I have more components which update records I have extracted "updateRecordWithToast" to separate util class lwc_utils.
Imported to prevous one using:
import { updateRecordWithToast} from 'c/lwc_utils';
Then for success update when there is no error I am getting in console:
Uncaught (in promise) TypeError: Cannot read property 'message' of undefined
at eval (lwc_utils.js:4)
Which basically mean that message: error.body.message is undefined which is true in case of success update.
But I do not understand why error branch is evaluated?
Is there any workaround to keep error message and avoid such error?
It breaks at this point so no toast is shown.
Best Answer
The problem is not in the update, the problem is in
return refreshApex(this.lead);
this.lead
does not exist, also when refresh apex gives an exception, the error does not contain body or message thuserror.body.message
is undefined. And your catch block is called.use
return refreshApex(this.recordInput);
and this will solve your problem