Sub topic 9
Saving changes with updateRecord
This chapter covers how to save edits to an existing record from a Lightning web component with updateRecord from lightning/uiRecordApi. It assumes you know JavaScript promises and async/await, the structure of a Lightning web component, the @api decorator with recordId, and the basics of Salesforce objects and fields. You should also have read the chapters on getRecord, schema imports, and wire results.
Reading uses a wire, updating uses a function
Earlier chapters used getRecord, which is a wire adapter. A wire adapter provisions data to your component whenever its inputs change. You declare it once, and the platform calls it for you.
updateRecord works differently. Saving is an action that you trigger at a specific moment, such as a button click. So updateRecord is an imperative function. You import it, call it, and it returns a promise.
| Row | `getRecord` | `updateRecord` |
|---|---|---|
| Kind | Wire adapter | Imperative function |
| Triggered by | Platform, when parameters change | Your code, when you call it |
| Returns | `{ data, error }` through the wire | A promise |
| Use for | Reading | Saving changes |
Do not put updateRecord inside @wire. It is not a wire adapter, and the component will not compile or behave correctly.
How updateRecord fits with the cache
Lightning Data Service (LDS) keeps a shared client-side cache of records. When updateRecord succeeds, LDS saves the change to the server and updates the cached copy of the record. Every wire that reads the same record, in this component or in any other component on the page, receives the new values.
This is the main benefit. You do not need to re-query or manually refresh after a successful updateRecord. Components that display the record update on their own.
The record input
updateRecord takes one argument, an object with a fields property. The fields object maps field API names to new values. It must include the Id field, so LDS knows which record to change.
const recordInput = {
fields: {
Id: '001000000000001AAA',
Name: 'Acme Corporation'
}
};Only include the fields you want to change, plus Id. Fields you leave out are not modified.
Build keys from schema imports
Hard-coded strings such as 'Name' work, but they are easy to mistype and the platform cannot track them as dependencies. Use the schema imports you learned earlier. Each imported field reference has a fieldApiName property that holds the API name.
import ID_FIELD from '@salesforce/schema/Account.Id';
import NAME_FIELD from '@salesforce/schema/Account.Name';
const fields = {};
fields[ID_FIELD.fieldApiName] = this.recordId;
fields[NAME_FIELD.fieldApiName] = this.newName;The fieldApiName of NAME_FIELD is the string 'Name'. Using the reference means that if the field is deleted or renamed, you find out at deploy time instead of at runtime.
A complete example
This component shows an input and a button on a record page. It saves the new name and shows a toast message for success or failure.
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'
})
);
}
}
}A matching template needs an input, a button, and the two handlers:
<template>
<lightning-card title="Rename account">
<div class="slds-var-p-around_medium">
<lightning-input
label="New name"
value={newName}
onchange={handleChange}
></lightning-input>
<lightning-button
label="Save"
variant="brand"
onclick={handleSave}
></lightning-button>
</div>
</lightning-card>
</template>The metadata file must expose the component to record pages, for example with the lightning__RecordPage target and the Account object.
Walking through handleSave
- The code builds a
fieldsobject with the recordIdand the new name. updateRecord({ fields })returns a promise. TheawaitpauseshandleSaveuntil the promise settles.- If the promise resolves, the record is saved and the cache is updated. The component shows a success toast.
- If the promise rejects, control jumps to the
catchblock. The component shows an error toast using the message from the error.
Handling errors from updateRecord
A rejected promise carries an error object. For Salesforce errors, the useful part is in error.body. Common causes of failure include:
- A validation rule rejects the new value.
- A required field is blank.
- The user does not have edit access to the record or to a field.
- The record was changed by someone else since it was loaded, and the update is rejected as a conflict.
- A trigger or flow throws an error during the save.
The shape of error.body varies. It can be an object with a single message, or it can hold field-level details in error.body.output.fieldErrors and page-level details in error.body.output.errors. A defensive handler reads the message safely:
function getErrorMessage(error) {
if (error && error.body) {
if (Array.isArray(error.body)) {
return error.body.map((e) => e.message).join(', ');
}
if (typeof error.body.message === 'string') {
return error.body.message;
}
}
return (error && error.message) || 'Unknown error';
}Use a helper like this so one place handles every shape. The error.body && error.body.message pattern in the main example is enough for simple cases but can return undefined when the message is in another location.
Optimistic behavior and what the user sees
After await updateRecord(...) resolves, the cache already holds the new values. A wired getRecord in the same component re-emits with the updated data, so templates bound to account.data refresh without extra code.
If the call fails, the cache is not changed. Wired components keep showing the old values, which is correct because the server never accepted the new ones. Your input fields, however, still hold what the user typed. Decide whether to leave that text so the user can fix it, or to reset it.
Preventing duplicate saves
Between the click and the promise settling, the user can click again. That sends a second update. Disable the button while a save is in flight:
isSaving = false;
async handleSave() {
this.isSaving = true;
try {
await updateRecord({ fields: this.buildFields() });
// success handling
} catch (error) {
// error handling
} finally {
this.isSaving = false;
}
}Bind disabled={isSaving} on the button in the template. The finally block runs on both outcomes, so the button always becomes active again.
Common mistakes
- Missing
Id. Without theIdkey, the call rejects. Always setfields[ID_FIELD.fieldApiName]. - Passing fields at the top level. The argument is
{ fields }, not the fields object itself. - Updating read-only or formula fields. These are not editable and cause an error. Only include fields the user can edit.
- Wrong value types. Send numbers as numbers and booleans as booleans. Dates and datetimes use ISO 8601 strings.
- Calling it from a wire.
updateRecordbelongs in an event handler or other code you control. - Expecting a wire to re-run. A wire does not re-run because you called
updateRecord. It receives the new value because the cache changed. If the server data changes in a way LDS does not know about, such as an Apex method, usegetRecordNotifyChangeas the next chapter explains.
Exercises
Exercise
Why is updateRecord imported and called as a function inside an event handler, instead of being declared with @wire?
Show answer
A wire adapter provisions data automatically when its inputs change, which suits reading. Saving is an action that must run at a specific moment, such as a button click, so updateRecord is an imperative function that returns a promise and that you call yourself.
Exercise
A component calls updateRecord({ fields: { Name: 'New Co' } }) and the promise rejects. What is the most likely cause, and how do you fix it?
Show answer
The fields object has no Id, so LDS cannot tell which record to update. Add the record ID, for example fields[ID_FIELD.fieldApiName] = this.recordId, using the imported Account.Id schema reference.
Exercise
After await updateRecord(...) succeeds, another component on the page shows the same account name through a getRecord wire. Do you need to write code to refresh it? Why?
Show answer
No. LDS updates the shared cache when the save succeeds, and every wire reading that record receives the new data. Extra refresh code is only needed when the record changes outside LDS, for example in Apex.