Sub topic 3
Saving Records with `updateRecord`
Assume you know JavaScript modules, promises, Lightning web component structure, and the @api recordId property. Reading with getRecord uses the wire service. Saving with updateRecord is imperative: your code calls the function when the user submits a change.
Saving changes with `updateRecord`
Pass updateRecord an object whose fields property contains API field names. Include the record ID. The function returns a promise.
import { LightningElement, api } from 'lwc';
import { updateRecord } from 'lightning/uiRecordApi';
import ID_FIELD from '@salesforce/schema/Account.Id';
import NAME_FIELD from '@salesforce/schema/Account.Name';
export default class AccountRename extends LightningElement {
@api recordId;
newName = '';
handleChange(event) {
this.newName = event.target.value;
}
async handleSave() {
const fields = {};
fields[ID_FIELD.fieldApiName] = this.recordId;
fields[NAME_FIELD.fieldApiName] = this.newName;
try {
await updateRecord({ fields });
console.log('Account updated');
} catch (error) {
console.error(error.body?.message || 'Update failed');
}
}
}Schema imports provide field references and prevent hard-coded API names from becoming stale during development.
Handling read and update errors
A wired getRecord result can contain either data or error. An imperative update uses try and catch. Show a useful message in the template rather than exposing an object directly. Errors can result from missing access, validation rules, required fields, or invalid values.
Refreshing data after external changes
If Apex or another server operation changes a record outside Lightning Data Service, notify the record cache:
import { getRecordNotifyChange } from 'lightning/uiRecordApi';
getRecordNotifyChange([{ recordId: this.recordId }]);This lets wired getRecord consumers receive fresh values.
Related choices
Use getRecordUi when you need record data together with layout and metadata. Use getRecordCreateDefaults to prepare a new-record form. Use getRecords when retrieving several records. For standard create, edit, or view behavior, base record form components often require less code than custom uiRecordApi logic.
Testing a wired component
Mock the lightning/uiRecordApi module in Jest. Emit a mock getRecord value, assert the rendered fields, then emit an error and assert the error message. For saving, mock updateRecord and verify it receives the expected field map.
Exercise
Which function should you call after Apex changes a record that a component reads with getRecord?
Show answer
Call getRecordNotifyChange with the changed record ID so Lightning Data Service can refresh its cached data.