How to use lightning data service in lightning web components(LWC)

Lightning data service allows you to cache and share data between lightning components using browser cache. Lightning framework takes care of managing cached data in browser. You do not need to write any code to interact with browser cache. There is no need to write any apex code also. Since the data is coming from client/browser cache, you can access data quickly if it is cached already. Lightning data service is built on top of Salesforce user interface API.

Use cases

  • Create simple forms that can create/view/edit single record.
  • lightning-record-form can be used to display data from all fields in standard page layout.
  • If you are building a component to use in a record details page and the component only updates the fields in the same record, it is highly recommended to use lightning data service, since Salesforce keeps data in sync with details page automatically.


Explanation

You can use "getRecord" and "updateRecord" methods from "lightning/uiRecordApi" to get record and update record from lightning data service respectively. After getting a record you need to wire it to a variable to make it available in UI. Then you need to use "getFieldValue" method and create a getter method to make the field available in the UI.

If we go step by step in the flow, below actions happen in a sequence when the component is loaded and value is changed.

  1. Component gets loaded in a record details page and salesforce passes "recordId" attribute is passed in to the component
  2. @wire annotation uses "getRecord" to get data from Salesforce server using lightning data service
  3. This data is made available to HTML through "checkboxValue" getter method. At this point if the data in contact record is checked, it will be dispalyed in UI
  4. Say user changed the value of checkbox by clicking it. "handleFieldChange" method is called. This method creates an object to update and passes to "updateContact" method
  5. "updateContact" method uses "updateRecord" method from lightning data service to send this data to Salesforce server and update
  6. Based on success or failure, a toast message is shown by firing an eveng


How to use

  • This code assumes that you have a checkbox field in your contact object with API name "My_Checkbox_Field__c"
  • Create an LWC component with name "lwcDataserviceComponent". Copy HTML, JS and XML code above to relevant files
  • Once the component is saved, you should be able to see it in app builder interface for contact object. This is because we have made it available through the metadata file of lightning component
  • Drag and drop the component to contact page and activate it
  • If you have the same field in record details section, you will be able to see that getting updated in real time as you update the checkbox in the lwc component.

No comments:

Post a Comment