Sub topic 9
Saving changes with updateRecord
This chapter assumes you can write a Lightning web component with an @api recordId, you know async/await, and you have already wired getRecord to display a record. Reading uses a wire adapter. Updating does not. updateRecord is an imperative function that you call when the user acts, and it returns a promise.
How updateRecord works
updateRecord is exported from lightning/uiRecordApi. You pass it a record input object with a fields property. That object must contain the record Id plus each field you want to change. It sends the change to the server through Lightning Data Service (LDS). When the save succeeds, LDS updates its shared cache, and every wire that reads the same record receives the new values. You don't refresh anything by hand.
Building the record input
Import field references from @salesforce/schema, as you did for reads. Use their fieldApiName property as the key, so you never hard-code a name.
import { LightningElement, api } from 'lwc';
import { updateRecord } from 'lightning/uiRecordApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
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 });
this.dispatchEvent(
new ShowToastEvent({ title: 'Success', message: 'Account updated', variant: 'success' })
);
} catch (error) {
this.dispatchEvent(
new ShowToastEvent({
title: 'Error updating record',
message: error.body && error.body.message,
variant: 'error'
})
);
}
}
}The code does three things:
- It builds a
fieldsobject with theIdand the one field that changed. - It awaits
updateRecord. The call is insidetry, so a rejected promise lands incatch. - It shows a toast for success or failure.
A matching template needs an input and a button:
<template>
<lightning-input label="New name" value={newName} onchange={handleChange}></lightning-input>
<lightning-button label="Save" onclick={handleSave}></lightning-button>
</template>What to send
Send only the Id and the fields that changed. Fields you leave out stay as they are. Without the Id, the call fails, because LDS cannot tell which record to change.
Handling failure
A rejected promise carries an error object. The readable text is usually in error.body.message. Validation rules, required fields, and missing permissions all produce errors this way. Some errors list per-field problems in error.body.output.fieldErrors. Check that the body exists before reading it, as the example does, because network failures may not have one.
Updates and wired data
A wired getRecord that reads the same record updates by itself after a successful save. Any other component on the page that wires that record updates too. This works because all of them read from the same cache.
Common mistakes
| Mistake | Result | Fix |
|---|---|---|
| Leaving out the `Id` | The update is rejected | Add `ID_FIELD.fieldApiName` to `fields` |
| Hard-coding `'Name'` as a key | Breaks if the schema reference changes, and misses dependency tracking | Use `NAME_FIELD.fieldApiName` |
| Not awaiting the promise | Errors go uncaught, and success toasts fire early | Use `await` in `try`/`catch` |
| Sending every field | Extra permission failures | Send only changed fields |
Exercise
A component calls updateRecord({ fields }) successfully, and a second component on the same page wires getRecord for the same record. Does the second component need extra code to show the new value? What if the change had been made by an Apex method instead?
Show answer
No extra code is needed after updateRecord. LDS updates the shared cache, and the wire provisions the new data. After an Apex change, LDS is unaware of it, so the component must call getRecordNotifyChange([{ recordId }]) to refresh the wired data.
Exercise
Why must the fields object passed to updateRecord contain the record's Id, and which fields besides the Id should it contain?
Show answer
The Id tells LDS which record to update. Besides the Id, include only the fields whose values changed.