Detect record update in Salesforce Lightning Web Component

Detect record update in Salesforce Lightning Web Component

Learn how to detect real-time record updates in Salesforce Lightning Web Components (LWC) using the getRecord adapter from the lightning/uiRecordApi module.


How to Detect Record Updates in Salesforce LWC Using getRecord

Keeping your user interface synchronized with the backend database is a fundamental requirement in modern web applications. In the Salesforce ecosystem, Lightning Web Components (LWC) makes this incredibly seamless. If you are a Salesforce Developer or Architect looking to build highly reactive components, understanding how to detect record updates without writing unnecessary Apex is crucial.

In this post, we will explore how to use the getRecord wire adapter from the lightning/uiRecordApi module to automatically detect and reflect record updates in your LWC.


Why Use lightning/uiRecordApi?

Historically, fetching and detecting changes in Salesforce records required custom Apex controllers and manual imperative calls. Today, the Lightning Data Service (LDS) handles this natively on the client side.

By leveraging the getRecord adapter, your component automatically subscribes to LDS. When a record is updated—LDS detects the change in its cache and automatically provisions the updated data back to your wired property. This means your component re-renders instantly with the fresh data, ensuring a unified user experience.


Component Architecture Overview

To demonstrate this, we will build a simple AccountDetails component. This component sits on an Account Record Page, retrieves standard fields, and updates reactively if those fields are modified.

FilePurpose
HTMLDefines the UI layout using Lightning Design System (SLDS) classes.
JavaScriptHandles the reactive @wire service and data population.
XMLExposes the component to the Lightning App Builder for Record Pages.

Sample Implementation: Account Details LWC

Below is the complete code for our component. It relies strictly on standard LWC decorators (@api, @wire) and the getRecord adapter.

1. The Template (accountDetails.html)

<template>
    <lightning-card title="Account Details">
        <div class="slds-p-horizontal_medium">
            <p><strong>Name:</strong> {accountName}</p>
            <p><strong>Industry:</strong> {accountIndustry}</p>
            <p><strong>Phone:</strong> {accountPhone}</p>
            <p><strong>Website:</strong> {accountWebsite}</p>
        </div>
    </lightning-card>
</template>

2. The Controller (accountDetails.js)

import { LightningElement, wire, api } from 'lwc';
import { getRecord } from 'lightning/uiRecordApi';

/**
 * Retrieves and displays key fields from an Account record
 * using the wire service and the getRecord adapter.
 */
export default class AccountDetails extends LightningElement {

    /** Record Id of the current Account, set by the hosting page */
    @api recordId;

    accountName;
    accountPhone;
    accountWebsite;
    accountIndustry;

    /**
     * Wire adapter — fetches the Account record.
     * Populates account field properties on success; logs errors on failure.
     *
     * @param {object} data  - Resolved record payload
     * @param {object} error - Error object when the request fails
     */
    @wire(getRecord, { 
        recordId: '$recordId', 
        layoutTypes: ['Full'], 
        modes: ['View'] 
    })
    wiredAccount({ error, data }) {
        if (data) {
            this.accountName     = data.fields.Name.value;
            this.accountPhone    = data.fields.Phone.value;
            this.accountWebsite  = data.fields.Website.value;
            this.accountIndustry = data.fields.Industry.value;
        } else if (error) {
            console.error('Error fetching account record:', error);
        }
    }
}

3. The Configuration (accountDetails.js-meta.xml)

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>66.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>
</LightningComponentBundle>

How the Update Detection Works

Lightning Data Service (LDS) is the centralized data management layer for Lightning Web Components (LWC). Think of it as a smart, client-side cache that ensures data consistency and performance across your entire application.


Key Benefits & Core Concepts

  • Single Source of Truth: Records are cached and shared. If multiple components use the same record, they all display the same version.
  • Performance Optimization: LDS loads a record once. Subsequent requests from other components are served from the cache, reducing server round-trips.
  • Automatic Updates: When one component updates a record, LDS automatically pushes that change to every other component using that same data.
  • Built on UI API: LDS leverages the Salesforce User Interface API, meaning it automatically respects CRUD permissions, Field-Level Security (FLS), and sharing rules.

How to Use LDS

You can interact with LDS through three primary technologies:

  1. Base Components: The simplest way to create forms (e.g., lightning-record-form, lightning-record-view-form, lightning-record-edit-form).
  2. Wire Adapters & Functions: Using the lightning/ui*Api modules for more granular control over data and metadata.
  3. GraphQL API: For advanced, flexible data fetching via the GraphQL wire adapter.

LDS vs. Apex

FeatureLightning Data Service (LDS)Apex
ManagementFully managed by the framework.Manual management required.
CachingAutomatic client-side caching.No automatic client caching.
UpdatesReactive; changes reflect across components.Static; requires manual refresh/imperative calls.
SecurityAutomatically respects FLS and Sharing.Requires with sharing and manual FLS checks.

The Power of Caching

LDS performs several heavy-lifting tasks to ensure your app feels fast:

  • Progressive Loading: Loads data as needed.
  • Bulkification: Dedupes and combines server requests to save bandwidth.
  • Cache Invalidation: Automatically clears old data when it detects changes or when the cache expires.

Note on Metadata: Object and layout metadata are cached in a “durable store.” If an Admin changes a page layout, you may need to reload the page or log out/in to see the changes, as metadata has a different timeout than record data.


When Does Data Refresh?

LDS triggers a refresh if:

The user is in the same browser, app, and session where the change occurred.

A component mutates (updates) the record via LDS.

The cache entry expires and a @wire adapter triggers a new read.


Reference

https://developer.salesforce.com/docs/platform/lwc/guide/reference-wire-adapters-record.html

https://developer.salesforce.com/docs/platform/lwc/guide/data-ui-api.html

Leave a Reply