LWC getRecords wire adapter: how to retrieve records dynamically (2024)

Oleksandra Todorenko

Posted on • Updated on

LWC getRecords wire adapter: how to retrieve records dynamically (3) LWC getRecords wire adapter: how to retrieve records dynamically (4) LWC getRecords wire adapter: how to retrieve records dynamically (5) LWC getRecords wire adapter: how to retrieve records dynamically (6) LWC getRecords wire adapter: how to retrieve records dynamically (7)

#salesforce #lwc #wire #getrecords

In this article, I would like to share use cases, syntax, workarounds and features of using the getRecords wire adapter in the Lightning Web Components (LWC) framework in Salesforce.

Ways to retrieve record data in LWC

Development by using the LWC often includes some kind of operations with records in the database: creating, retrieving, updating, and deleting.

There are different ways to retrieve information about the record by its Id while working with LWC.
The simplest and the most limited is by using Lightning Base Components such as “lightning-record-form” or “lightning-record-view-form”. You can retrieve field labels and values for the specific record id and that’s it. The most customizable way is, as always, calling custom Apex. You can retrieve all the needed record details. However, every call to the backend takes more time than operations on the client-side and Apex methods should be called imperatively.
In case you have ids of records (even of different objects!) and want to retrieve their field values (translated and original ones), record type, or last modified details, I recommend using the @wire getRecord or getRecords adapter.

getRecord vs getRecords comparison

These two wire adapters are very similar - both of them belong to 'lightning/uiRecordApi', and accept record id(s) and fields to retrieve parameters.
The only thing is that getRecords operates over an array of record ids instead of only one id. For sure, it can accept an array that contains only one id.
Also, getRecords returns a collection of batch result records - each record for each provided id.
If you are unaware of how many record ids should be processed or if you expect more than one id, consider using the getRecords adapter.

Syntax

import { LightningElement, wire } from 'lwc';import { getRecords } from 'lightning/uiRecordApi';@wire(getRecords, { records: [ { recordIds: string[], fields: string[] } ] })propertyOrFunction@wire(getRecords, { records: [ { recordIds: string[], fields: string[], optionalFields?: string[] } ] })propertyOrFunction

More details you may find in the official documentation.

Please note: usage of fields or optionalFields parameter is mandatory. The difference is that while using fields and the context user doesn’t have access to this field, an error occurs. If the user hasn’t access to the field from the optionalFields parameter - it doesn’t cause an error, just this field won’t be returned. Think about which approach is more convenient in your case and don’t forget that you can use both parameters at the same time.

How to retrieve records for dynamic record Ids

There are various examples of retrieving record data using getRecords for predefined ids for one or for several different objects. Please take a look at the examples from the Salesforce documentation.

For one object:

import { LightningElement, wire } from 'lwc';import { getRecords } from 'lightning/uiRecordApi';import NAME_FIELD from '@salesforce/schema/User.Name';import EMAIL_FIELD from '@salesforce/schema/User.Email';export default class GetRecordsExample extends LightningElement { @wire(getRecords, { records: [ { recordIds: ['005XXXXXXXXXXXXXXX', '005XXXXXXXXXXXXXXX'], fields: [NAME_FIELD], optionalFields: [EMAIL_FIELD] } ] }) wiredRecords;}

For multiple objects:

import { LightningElement, wire } from 'lwc';import { getRecords } from 'lightning/uiRecordApi';import USER_NAME_FIELD from '@salesforce/schema/User.Name';import USER_EMAIL_FIELD from '@salesforce/schema/User.Email';import ACCOUNT_NAME_FIELD from '@salesforce/schema/Account.Name';export default class GetRecordsExample extends LightningElement { @wire(getRecords, { records: [ { recordIds: ['005XXXXXXXXXXXXXXX'], fields: [USER_NAME_FIELD], optionalFields: [USER_EMAIL_FIELD] }, { recordIds: ['001XXXXXXXXXXXXXXX'], fields: [ACCOUNT_NAME_FIELD] }, ] }) wiredRecords;}

As for now, the main difficulty is the inability (almost) to retrieve records when there are no predefined ids and objects. They are set only statically and there’s no way to write them down dynamically in the array of objects.

In such an unusual case I recommend creating an array parameterObject that will include all record parameters as a single property.
This object can be created in the scope of connectedCallback, renderedCallback, or at the level of the parent component that calls the current one.
The format will look something like this:

this.recordIds.forEach(recordId =>{ this.parameterObject.push({ recordIds: [recordId], optionalFields: this.fieldsToRetrieve })});

This is the structure that will retrieve records dynamically for different objects when there’s no prepared structure of parameterObject with predefined Ids. Let’s consider an example of using the getRecords adapter when records should be retrieved dynamically.

Example of using getRecords for dynamic retrieving data for different objects

Let’s imagine a case when we need to retrieve contact records and the current user’s record and display them in the lightning datatable on Account’s record page.
As getRecords operates over record Ids, let’s create two components: parentComponent and childComponent. Method getContacts on the parent component will retrieve the Ids of contacts related to the current Account. Yes, we could retrieve all the record details at this stage from Apex, but we have this logic just to demonstrate a case when we have only Id and no other record data.

parentComponent.html. Here we transfer contactIds to the child component.

<template> <c-child-component record-ids={contactIds}></c-child-component> </template>

parentComponent.js

import { LightningElement, wire, api } from 'lwc';import getContacts from '@salesforce/apex/ContactController.getContactsByAccount';export default class ParentComponent extends LightningElement { @api recordId; //current Account's Id contactIds = []; @wire(getContacts, {accountId: '$recordId'}) retrievedContacts({error, data}){ if(data){ this.contactIds = data; } else if(error){ console.log('error: ', error); } }}

And Apex controller ContactController that retrieves contact Ids:

public with sharing class ContactController { @AuraEnabled(cacheable=true) public static List<Contact> getContactsByAccount(Id accountId) { return [ SELECT Id FROM Contact WHERE AccountId = :accountId ]; }}

The next one is childComponent.html. Here we display all the data in the form of a lightning-datatable Lightning Base Component.

<template> <template if:true={dataIsRetrieved}> <lightning-datatable data={dataToDisplay} columns={columnsToDisplay} key-field="id" hide-checkbox-column="true"> </lightning-datatable> </template></template>

And the last but not least part - childComponent.js.

import { LightningElement, wire, api, track } from 'lwc';import { getRecords } from 'lightning/uiRecordApi';import CONTACT_NAME_FIELD from '@salesforce/schema/Contact.Name';import CONTACT_EMAIL_FIELD from '@salesforce/schema/Contact.Email';import CONTACT_PHONE_FIELD from '@salesforce/schema/Contact.Phone';import USER_NAME_FIELD from '@salesforce/schema/User.Name';import USER_EMAIL_FIELD from '@salesforce/schema/User.Email';import USER_PHONE_FIELD from '@salesforce/schema/User.Phone';import userId from '@salesforce/user/Id';export default class ChildComponent extends LightningElement { dataIsRetrieved = false; contactIds = []; parameterObject; dataToDisplay = []; columnsToDisplay = [ { label: 'Object', fieldName: 'object'}, { label: 'Id', fieldName: 'id'}, { label: 'Name', fieldName: 'name' }, { label: 'Email', fieldName: 'email', type: 'email'}, { label: 'Phone', fieldName: 'phone', type: 'phone'}, { label: 'Last Modified Date', fieldName: 'lastModified', type: 'date'} ]; @api get recordIds(){ return this.contactIds; } set recordIds(contacts){ this.contactIds = contacts; this.parameterObject = []; if(this.contactIds.length > 0){ this.contactIds.forEach(contact => { this.parameterObject.push({ recordIds: [contact.Id], optionalFields: [CONTACT_NAME_FIELD, CONTACT_EMAIL_FIELD, CONTACT_PHONE_FIELD] }); }); this.parameterObject.push({ recordIds: [userId], optionalFields: [USER_NAME_FIELD,USER_EMAIL_FIELD, USER_PHONE_FIELD] }); } } @wire(getRecords, { records: '$parameterObject'}) wiredRecords({ err, data }) { if (err) { console.log('error: ',err); } else if (data) { this.dataIsRetrieved = true; console.log('getRecords results: ',data.results); data.results.forEach(record => { this.dataToDisplay.push({ name: record.result.fields.Name.value, email: record.result.fields.Email.value, id: record.result.id, phone: record.result.fields.Phone.value, object: record.result.apiName, lastModified: record.result.lastModifiedDate }); }); } }}

As you may see, getRecords uses ‘$parameterObject’ with all the parameters inside for retrieving records. A dollar sign $ means using a dynamic variable. The method will be called every time when the dynamic variable is updated. However, dynamic update works for getRecord and other methods that accept primitive types as a parameter, not a collection. That is why I recommend using parameterObject for getRecords. This parameterObject is an array that is filled dynamically when ids of contacts are received from the parentComponent. If the number of Ids or retrieved objects may vary, this is the best workaround for dynamic retrieval records using getRecords.

The final result is the following:

LWC getRecords wire adapter: how to retrieve records dynamically (8)

Summary

To sum up, getRecords is a very useful solution for some specific cases when record data should be retrieved by Id, especially from different objects - to minimize the amount of SOQL queries and calls to the backend.

If you found this article helpful, I invite you to connect with me on LinkedIn. I am always looking to expand my network and connect with like-minded individuals in the Salesforce area. Additionally, you can also reach out to me for any questions or feedback on the article. I'd be more than happy to engage in a conversation and help out in any way I can. So don’t hesitate to contact me, and let’s connect and learn together!

LWC getRecords wire adapter: how to retrieve records dynamically (2024)

FAQs

How to get record value in lwc? ›

To get the value of a record's field, you can use the getRecord wire adapter, which returns the property record. data. fields. fieldName.

What are adapters in LWC? ›

An adapter, in the context of LWC, is a utility function that connects your component to Salesforce data using the Wire Service. The `adapterId` is the identifier of the adapter you want to use, and `adapterModule` is the name of the module where the adapter is defined.

What is the use of wire method in LWC? ›

Using wire adapters you can import references to Salesforce Objects and Fields. Salesforce verifies that the objects and fields exist, prevents objects and fields from being deleted, and cascades any renamed objects and fields into your component's source code.

How do I retrieve data from LWC? ›

To retrieve data in an Apex controller from a Lightning Web Component (LWC), you can use the @AuraEnabled annotation on a method in the controller to make it accessible to the LWC. This component has a contacts property that is bound to the getContacts method using the wire decorator.

How to get record ID dynamically in LWC? ›

In order to retrieve the record id from the url, use @api recordId decorator. Using @api recordId, the record id will be passed from the url to the lwc component.

How to query a record in LWC? ›

Use getRecord and getFieldValue to get a record and display its fields values. Replace the recordId value with your own. Load the field values in a custom user interface.

Which wire adapter is used to get default values to create record in lwc? ›

The @wire(getRecord) adapter is used to retrieve a single record from Salesforce, identified by its record ID. This wire adapter is immensely valuable when you need to display or manipulate data from a specific record.

What is the difference between wire and imperative in LWC? ›

While the wire service in LWC provides an automatic, reactive link to your Apex data, imperative calls offer a more hands-on, controlled interaction. Which one you choose depends on your component's needs and your specific situation.

How many types of adapters are there? ›

There are currently 15 different socket types found around the world, 12 of which are considered to be common types. A handy first step in buying the right adapter for various plug types is learning to recognise the most widely-used types.

What is the difference between wire and track in LWC? ›

@track facilitates tracking of private reactive properties, ensuring automatic rerendering when their values change. Meanwhile, @wire enables reactive data fetching from Salesforce, resulting in dynamic and up-to-date components.

What is the best wire connection method? ›

A solder join - wires spliced together (preferred method).

How to pass record ID in wire method? ›

To pass a record ID from a Lightning Web Component (LWC) to Apex, you can define an Apex method in your Apex class that takes the record ID as a parameter, and then call this method from your LWC while passing the record ID as an argument.

How do I refresh wire data in LWC? ›

To refresh a wired method, pass the argument the wired method receives (which is the wired value) to refreshApex() . In this sample code, the wired method is wiredGetActivityHistory(value) . Hold on to the value provisioned by the wire service and pass it to refreshApex() .

How to fetch data from object in lwc? ›

Here's a step-by-step guide on how to fetch and display data in a Salesforce LWC:
  1. Create a Lightning Web Component: If you haven't already, create an LWC in your Salesforce environment. ...
  2. Define a Property to Hold Data: ...
  3. Fetch Data: ...
  4. Display Data in the Template: ...
  5. Deploy and Test: ...
  6. Handle Errors:
Nov 17, 2023

How do I retrieve data back? ›

How To Recover Deleted Files (2024 Guide)
  1. Check Your Recycle Bin.
  2. Use the Control Panel.
  3. Use a Data Recovery Software.
  4. Hire a Data Recovery Service.
  5. Bottom Line.
  6. Frequently Asked Questions (FAQs)
Jul 18, 2024

How do I get row data in LWC? ›

So here's a native way to get the selected rows. If you have multiple lightning-datatable elements use a id specifier like data-id or class to find your specific your datatable then use getSelectedRows() method on it.

How to fetch account record in lwc? ›

First, create a lightning web component page on any record page (Account, Opportunity, contact) using Visual studio code. We are creating this LWC to get account details. Give any name to the LWC page as we are giving as recordIdexample. Use Control Shift P and select SFDX: Create lightning Web Component.

How to get current record field value in lightning component? ›

Just implement your aura component with force:hasRecordId & you'll get record id of the current record. Use LDS(Lightning data service) to get JobTitle field of the current record). Make an Apex call to get the related records.

How to get user record in lwc? ›

To get information about the current user, use the @salesforce/user scoped module. import property from "@salesforce/user/property"; property —The supported properties are Id , which is the user's ID, and isGuest , which is a boolean value indicating whether the user is a guest user.

Top Articles
Latest Posts
Article information

Author: Sen. Ignacio Ratke

Last Updated:

Views: 5994

Rating: 4.6 / 5 (56 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Sen. Ignacio Ratke

Birthday: 1999-05-27

Address: Apt. 171 8116 Bailey Via, Roberthaven, GA 58289

Phone: +2585395768220

Job: Lead Liaison

Hobby: Lockpicking, LARPing, Lego building, Lapidary, Macrame, Book restoration, Bodybuilding

Introduction: My name is Sen. Ignacio Ratke, I am a adventurous, zealous, outstanding, agreeable, precious, excited, gifted person who loves writing and wants to share my knowledge and understanding with you.