[SalesForce] LWC – How to get a record from within a javascript function

LWC newbie here. I am creating a LWC that will go on record pages of specified objectApiNames. When the user clicks the button in my LWC, depending on objectApiName I have to retrieve certain SObjects in order to make some decisions as to where to redirect the user (no retrieved data needs to be rendered in my LWC).

Most samples of getting data are focused on data that needs to be rendered and/or @wired/getRecord. I don't see any way to use getRecord from within a js function. Am I missing something here?

Of course the other option is to call an APEX function to the data retrieval.

Best Answer

Take a look at the uiRecordApi's getRecord service. The record returned contains the API name, as you can see in the documentation. Using this info you can get the current page's record's type thus:

@wire(getRecord, { recordId: "$recordId" })
handleRecord({ error, data }) {
    if (data) {
        const objectApiName = data.apiName;
        ...
    }
}

You can ask for various fields in subsequent wire invocations of this same service by having those depend on properties of your LWC that are set in the initial record retrieval when certain object API names are retrieved.

E.g. you could have "contactId" that gets set to the record's Id in "handleRecord" when the apiName is "Contact" then have a subsequent wire like:

@wire(getRecord, { recordId: "$contactId", /* ask for fields here */ })
handleContactRecord({ error, data }) {
    ...
}

and in this case then extract values from the contact to do what you need in that case.

The benefit of this approach is that getRecord will quite likely not actually perform any server round-trip at all since the record is already cached in the page (at least with the fields shown in the page).

Related Topic