Understanding LDS (Lightning Data Service) in Salesforce LWC

Understanding LDS (Lightning Data Service) in Salesforce LWC
Chinmaya By Chinmaya
8 Min Read

Introduction

Lightning Data Service (LDS) is a powerful tool in Salesforce’s Lightning Web Components (LWC) framework that simplifies working with Salesforce data.
It enables components to access, create, update, or delete Salesforce records without writing Apex code, leveraging the Lightning Data Service to manage data efficiently and ensure consistency across components.

In this blog, we’ll dive into the key concepts of LDS, its benefits, and practical examples of its usage in LWC.

What is Lightning Data Service (LDS)?

Lightning Data Service (LDS) is Salesforce’s mechanism for managing and sharing record data between Lightning components. It uses Salesforce’s native data caching layer to:

    • Avoid redundant server calls.
    • Automatically handle field-level security and sharing rules.
    • Maintain consistency when multiple components access the same data.

Benefits of Using LDS

  1. No Apex Code Required: Fetch, modify, and save data without writing any server-side code.
  2. Automatic CRUD Operations: Supports create, read, update, and delete (CRUD) operations.
  3. Handles Security: Automatically respects sharing rules and field-level security.
  4. Efficient Caching: Reduces the number of server calls by caching records.
  5. Real-Time Updates: Synchronizes data between components when the same record changes.

Core Features of LDS

  1. Declarative Record Access: Fetch and display Salesforce records with ease.
  2. CRUD Operations: Perform Create, Read, Update, and Delete actions.
  3. Automatic Data Refresh: If a record changes elsewhere, LDS updates the component automatically.
  4. Error Handling: LDS provides standardised error messages for smoother debugging.

How to Use LDS in LWC

LDS provides two primary approaches for working with records:

1. Using Base Lightning Components

These pre-built components provide the quickest way to implement common record operations

    • lightning-record-form : It is the Quickest way to display/edit records.
    • lightning-record-view-form : When you need a read-only display.
    • lightning-record-edit-form : When you need full control over the edit form.

2. Using Wire Adapters for Custom Implementations

For more complex scenarios, LDS provides direct wire adapters:

    1. getRecord
    2. getRecordCreateDefaults

Let’s explore each approach with examples.

Example 1: Display a Record Using 'lightning-record-form'

The easiest way to display a record is by using the lightning-record-form component. It requires minimal code.

Html

				
					<template>
    <lightning-record-form
        record-id="003XXXXXXXXXXXXXXX" <!-- Replace with your record Id -->
        object-api-name="Contact"
        layout-type="Full"
        mode="view">
    </lightning-record-form>
</template>
				
			

Explanation:

    • record-id: The ID of the record to fetch.
    • object-api-name: The object the record belongs to (e.g., Contact, Account).
    • layout-type: Controls the form layout (Compact or Full).
    • mode: Determines the mode (view, edit, or readonly).

Example 2: Custom Record Display Using 'lightning-record-view-form'

  1. Purpose: Read-only record display

  2. Features:

      • Customizable field layout

      • Respects field-level security

				
					<template>
    <lightning-record-view-form record-id="003XXXXXXXXXXXXXXX" object-api-name="Contact">
        <lightning-output-field field-name="FirstName"></lightning-output-field>
        <lightning-output-field field-name="LastName"></lightning-output-field>
        <lightning-output-field field-name="Email"></lightning-output-field>
    </lightning-record-view-form>
</template>
				
			

Example 3: Using 'lightning-record-edit-form'

For creating and editing records, <lightning-record-edit-form> offers a declarative way to handle form submissions.

Example 1: Creating a Record

				
					<!-- createRecord.html -->
<template>
    <lightning-record-edit-form object-api-name="Account">
        <lightning-messages></lightning-messages>
        <lightning-input-field field-name="Name"></lightning-input-field>
        <lightning-input-field field-name="Phone"></lightning-input-field>
        <lightning-input-field field-name="Industry"></lightning-input-field>
        <lightning-button type="submit" label="Create Account"></lightning-button>
    </lightning-record-edit-form>
</template>
				
			

Explanation:
The lightning-record-edit-form automatically handles record creation, including validation and saving data to Salesforce.

    • lightning-record-edit-form: Enables inline editing.
    • lightning-messages: Displays system messages like validation errors.
    • lightning-input-field: Allows editing of specific fields.

Example 2: Editing a Record

Html:

				
					<!-- editRecord.html -->
<template>
    <lightning-record-edit-form record-id="001XXXXXXXXXXXXXXX" object-api-name="Account">
        <lightning-messages></lightning-messages>
        <lightning-input-field field-name="Name"></lightning-input-field>
        <lightning-input-field field-name="Phone"></lightning-input-field>
        <lightning-input-field field-name="Industry"></lightning-input-field>
        <lightning-button type="submit" label="Update Account"></lightning-button>
    </lightning-record-edit-form>
</template>
				
			

Explanation:
This form fetches the account record, displays its fields for editing, and handles updates when the form is submitted.

    • lightning-record-edit-form: Enables inline editing.
    • lightning-messages: Displays system messages like validation errors.
    • lightning-input-field: Allows editing of specific fields.

4. Using @wire to Fetch Data Programmatically

LWC provides @wire to declaratively fetch data using Lightning Data Service. Common wire adapters include:

    • getRecord: Fetch a single record.
    • getRecordUi: Fetch a record along with metadata.
    • getObjectInfo: Fetch metadata for an object.

Example: Fetching a Single Record

Javascript:

				
					// accountRecord.js
import { LightningElement, wire } from 'lwc';
import { getRecord } from 'lightning/uiRecordApi';

const FIELDS = ['Account.Name', 'Account.Phone', 'Account.Industry'];

export default class AccountRecord extends LightningElement {
    recordId = '001XXXXXXXXXXXXXXX'; // Example Record ID

    @wire(getRecord, { recordId: '$recordId', fields: FIELDS })
    account;

    get accountName() {
        return this.account.data ? this.account.data.fields.Name.value : 'N/A';
    }

    get accountPhone() {
        return this.account.data ? this.account.data.fields.Phone.value : 'N/A';
    }

    get accountIndustry() {
        return this.account.data ? this.account.data.fields.Industry.value : 'N/A';
    }
}
				
			

Html

				
					<!-- accountRecord.html -->
<template>
    <p>Account Name: {accountName}</p>
    <p>Phone: {accountPhone}</p>
    <p>Industry: {accountIndustry}</p>
</template>
				
			

Explanation:
The getRecord adapter fetches the account record and provides reactive data to the component.

Example: Fetching Object Metadata

Javascript:

				
					// objectMetadata.js
import { LightningElement, wire } from 'lwc';
import { getObjectInfo } from 'lightning/uiObjectInfoApi';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';

export default class ObjectMetadata extends LightningElement {
    @wire(getObjectInfo, { objectApiName: ACCOUNT_OBJECT })
    accountMetadata;

    get accountLabel() {
        return this.accountMetadata.data
            ? this.accountMetadata.data.label
            : 'N/A';
    }

    get accountFields() {
        return this.accountMetadata.data
            ? Object.keys(this.accountMetadata.data.fields).join(', ')
            : 'No fields available';
    }
}
				
			

Html

				
					<!-- objectMetadata.html -->
<template>
    <p>Object Label: {accountLabel}</p>
    <p>Fields: {accountFields}</p>
</template>
				
			

Key LDS Adapters:

Use of different LDS Adapters

    • getRecord : Fetch a record.
    • getRecordCreateDefaults : Get default values for a new record.
    • createRecord : Create a new record.
    • updateRecord : Update an existing record.
    • deleteRecord : Delete a record.

LDS vs. Apex: When to Use Which?

FeatureLDSApex
Basic CRUD✅ Best⚠ Overkill
Complex Logic❌ No✅ Required
Performance✅ OptimizedDepends
Auto-Caching✅ Yes❌ No
Record Access✅ FLS Aware✅ (With sharing)

When to Use LDS?

  • Simple record operations

  • When you need automatic UI updates

  • To reduce Apex dependency

When to use Apex ?

  • Complex validation rules

  • Transactional operations (multiple records)

  • When needing SOQL/SOSL queries

Comparison: Wire Adapters vs. Record Edit Forms

FeatureLDS Wire Adapters (getRecordupdateRecord)Record Edit Forms (lightning-record-edit-form)
ImplementationJavaScript code (imperative)Declarative HTML markup
Control LevelHigh (full programmatic control)Medium (pre-built with customization options)
Best ForCustom UIs, complex logicStandard forms, rapid development
Data HandlingManual field managementAutomatic field rendering
Error HandlingManual implementationBuilt-in basic handling
Code VolumeHigh (~20-30 lines)Low (~5-10 lines)
PerformanceOptimized (fetch only needed data)Good (may load full layout)
ValidationCustom validation possibleBasic field-level validation
UI FlexibilityComplete freedomLimited to component’s design
Learning CurveSteeper (requires JS knowledge)Easier (mostly configuration)
Use Case ExampleDashboard components, complex editorsStandard object edit pages

Rule of Thumb:

    • Use Record Forms for 80% of standard CRUD operations
    • Use Wire Adapters when you need custom behavior or complex logics

Best Practices for Using LDS

    1. Use LDS Whenever Possible: Avoid writing custom Apex unless required for complex business logic.
    2. Avoid Redundant Queries: Use the same @wire adapter across components to leverage LDS caching.
    3. Leverage Error Handling: Handle errors gracefully when using wire adapters or record-edit forms.
    4. Respect Security: LDS ensures that field-level security and sharing rules are respected, but double-check access permissions for your component.

Conclusion

Lightning Data Service (LDS) makes working with Salesforce data in LWC straightforward and efficient.
By using @wire and <lightning-record-edit-form>, developers can interact with Salesforce data declaratively, reduce code complexity, and ensure security and consistency.

With its caching mechanism and real-time updates, LDS is a must-know for Salesforce developers who want to build scalable and high-performance applications.

Share This Article
Follow:
Chinmaya is working as a Senior Consultant with a deep expertise in Salesforce. Holding multiple Salesforce certifications, he is dedicated to designing and implementing cutting-edge CRM solutions. As the creator of Writtee.com, Chinmaya shares his knowledge on educational and technological topics, helping others excel in Salesforce and related domains.
Leave a comment