Lightning Data Service (LDS) with Real-time Examples and Code

Lightning Data Service Salesforce Shastras

Are you in the Salesforce world and looking to understand Lightning Data Service (LDS)? If so, you’re in the right place. We’ll uncover this brilliant platform, and by the end of this guide, you’ll have a good understanding of LDS, its implementation, and its benefits. Not only this, but we’ll also discuss a real-time example with integrative code for better comprehension.

Introduction to Lightning Data Service

What is Lightning Data Service (LDS)?

The Lightning Data Service (LDS) is a standard controller for Lightning Components. It provides a layer of data from Salesforce with JavaScript-based service, enabling you to create, read, update and delete records without writing Apex code.

Features of Lightning Data Service (LDS)

  • Shared, standardized cache
  • Leverages the UI API
  • Reduces server trips
  • No need for Apex

Need for Lightning Data Service (LDS)

In today’s technology-driven world, developers need a reliable method to access Salesforce data while reducing server trips. This is where LDS makes its entry. It loads data once and shares it with other components, eliminating redundant trips to the server.


Lightning Data Service (LDS) vs Apex

While both LDS and Apex are essential parts of Salesforce architecture, they cater to different requirements. LDS is a client-side controller designed to simplify data access and caching, whereas Apex is server-side coding that offers significantly more advanced solutions.


Tools of Lightning Data Service (LDS)

lightning/uiRecordApi Module:

  • This module provides functions and methods for working with records and their data using Lightning Data Service. Key functions include:
    • getRecord: Fetches a record’s data.
    • getRecordCreateDefaults: Fetches default values for creating a record.
    • updateRecord: Updates a record with new field values.
    • createRecord: Creates a new record.
    • deleteRecord: Deletes a record.
import { getRecord, updateRecord, createRecord, deleteRecord } from 'lightning/uiRecordApi';

@wire Decorator:

  • The @wire decorator is used to wire a Lightning web component to a function that retrieves data. In the context of LDS, it is often used to wire records to the component.
@wire(getRecord, { recordId: '$recordId', fields: ['Account.Name', 'Account.Industry'] })
account;
  1. User Interface API (UI API):
    • UI API is a RESTful API provided by Salesforce that allows developers to access metadata and data for Salesforce objects. It is a key component of LDS and is used to dynamically generate forms and handle record layouts in Lightning components.
  2. getRecordNotifyChange Function:
    • This function is used to subscribe to changes in a record. When a record changes, you can call this function to notify other components that are interested in the same record to refresh their data.
import { getRecordNotifyChange } from 'lightning/uiRecordApi';

// Call this function to refresh the record when changes occur
getRecordNotifyChange([{ recordId: 'recordId' }]);

Lightning Data Service Debugger:

  • The Lightning Data Service Debugger is a Chrome Developer Tools extension provided by Salesforce. It allows developers to inspect the state of records in the LDS cache, view queries, and debug interactions between components and LDS.

Real-time Example: Building a Task Manager with Lightning Data Service (LDS)

Building A Simple Lightning Data Service (LDS) Web Component:

Let’s create a simple Task Manager application using Lightning Data Service. Our application will display a list of tasks, allow users to mark tasks as completed, and add new tasks.

1. Create a Lightning Web Component

<!-- taskManager.html -->
<template>
    <lightning-card title="Task Manager" icon-name="utility:checklist">
        <div class="slds-m-around_medium">
            <lightning-input label="New Task" value={newTask} onchange={handleTaskChange}></lightning-input>
            <lightning-button label="Add Task" onclick={addTask}></lightning-button>
        </div>
        <lightning-datatable
            key-field="Id"
            data={tasks}
            columns={columns}
            onrowselection={handleRowSelection}
            selected-rows={selectedRows}>
        </lightning-datatable>
    </lightning-card>
</template>

2. Create JavaScript Controller

// taskManager.js
import { LightningElement, wire, track } from 'lwc';
import { refreshApex } from '@salesforce/apex';
import getTasks from '@salesforce/apex/TaskManagerController.getTasks';
import addTask from '@salesforce/apex/TaskManagerController.addTask';

export default class TaskManager extends LightningElement {
    @track newTask = '';
    @track tasks = [];
    @track columns = [
        { label: 'Task Name', fieldName: 'Subject', type: 'text' },
        { label: 'Due Date', fieldName: 'ActivityDate', type: 'date' },
        { label: 'Status', fieldName: 'Status', type: 'text' }
    ];
    @track selectedRows = [];

    _wiredTaskData;
    @wire(getTasks)
    retrieveOpportunities(wireResult){
        const { data, error } = wireResult;
        this._wiredTaskData = wireResult;
        if(data){
            console.log("Task Data", data)
            this.tasks = data
        }
        if(error) {
            console.error(error)
        }
    }

    handleTaskChange(event) {
        this.newTask = event.target.value;
    }
    addTask() {
      
        addTask({ name: this.newTask })
            .then(() => {
                // Optionally, refresh the wired data
                return refreshApex(this._wiredTaskData);
            })
            .catch(error => {
                // Handle error
                console.error('Error adding task: ' + error);
            });
    }
    handleRowSelection(event) {
        this.selectedRows = event.detail.selectedRows;
    }
}

3. Create Apex Controller

/**
 * @description       : Apex Class to get and Create Task for Task Manager Application
 * @author            : Abhishek Verma
 * @group             : Salesforce Shastras
 * @last modified on  : 01-21-2024
 * @last modified by  : Abhishek Verma
**/
// TaskManagerController.cls
public with sharing class TaskManagerController {
    @AuraEnabled(cacheable=true)
    public static List<Task> getTasks() {
        return [SELECT Id, Subject, ActivityDate, Status FROM Task ORDER BY CreatedDate DESC LIMIT 10];
    }

    @AuraEnabled
    public static void addTask(String name) {
        Task newTask = new Task(Subject = name, Status = 'Open');
        insert newTask;
    }
}

In this example, we’ve created a simple Task Manager application using Lightning Data Service. The getTasks Apex method retrieves the latest tasks, and the addTask method adds a new task. The Lightning web component uses LDS to display and manipulate the task data in a responsive and efficient manner.

By leveraging Lightning Data Service, developers can streamline the development process, reduce server calls, and create highly responsive Lightning components.


Understanding Lightning Data Service (LDS) Framework

There are three components to the Lightning Data Service (LDS) architecture:

1. Lightning Data Service Cache

The data cache is a client-side storage mechanism that stores records and their fields retrieved from Salesforce. It enables Lightning components to access data without making additional server requests.

2. User Interface API (UI API)

LDS communicates with the Salesforce User Interface API to retrieve metadata about the objects and fields in the org. UI API responses are used to dynamically generate forms and handle record layouts in Lightning components.

3. Lightning Component Framework

LDS seamlessly integrates with the Lightning Component Framework, allowing components to declaratively access and manipulate Salesforce data. Components subscribe to changes in the cache, enabling real-time updates.


Conclusion

The Lightning Data Service (LDS) is a seminal feature of Salesforce that’s optimized for both developers and end users. With its functionality and efficiency, LDS leads to fewer server trips and improved app performance, while decreasing the need for Apex in data-centric applications. Make sure you grasp its fundamentals and best practices to make the most out of this brilliant service.

Reference

Lightning Data Service

Lightning Web Components

One thought on “Lightning Data Service (LDS) with Real-time Examples and Code

Leave a Reply

Your email address will not be published. Required fields are marked *