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.


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).

  • Thanks for the reply but like I mentioned I want to get a record after a button is pressed so I need to make the call to get the record withing a JS function.
    – Homerlex
    Nov 15 '19 at 13:10
  • No you don't - you just have to set a property when that button is pressed that then triggers the wire to invoke. I have given the hint as to how to do this with the discussion of contactId.
    – Phil W
    Nov 15 '19 at 14:02

If you try to use getRecord imperatively like in JS,

        getRecord({ recordId: '$recordId', layoutTypes: ['Full'], modes: ['View'] }).then(result=>{

You get this exception:

enter image description here

So to say, there is no way to call getRecord from JS directly.

  • Yes, that's what I figured. So I am looking for other options. Calling APEX, which is an acceptable solution, may just be the way to go. I just would have expected some way to do this from LWC.
    – Homerlex
    Nov 15 '19 at 13:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.