0

I have a component which I'd like to present the real-time value of my record's fields. Considering simplified getFieldValue(record, field) Docs Example:

HTML:

<template>
    <lightning-card
        title="WireGetFieldValue"
        icon-name="standard:account">
        <template if:true={account.data}>
            <div class="slds-m-around_medium">
                <p><lightning-formatted-number 
                    format-style="currency"
                    value={revenue}
                    currency-code="USD">
                    </lightning-formatted-number>
                </p>
                <p>
                    <lightning-formatted-date-time
                    weekday="long"
                    month="short"
                    year="numeric"
                    day="2-digit"
                    hour="2-digit"
                    minute="2-digit"
                    value={created}>
                    </lightning-formatted-date-time>
                </p>
            </div>
        </template>
    </lightning-card>
</template>

JS:

import { LightningElement, api, wire } from 'lwc';
import { getRecord, getFieldValue } from 'lightning/uiRecordApi';

import REVENUE_FIELD from '@salesforce/schema/Account.AnnualRevenue';
import CREATED_FIELD from '@salesforce/schema/Account.CreatedDate';

const fields = [REVENUE_FIELD, CREATED_FIELD];

export default class WireGetValue extends LightningElement {
    @api recordId;

    @wire(getRecord, { recordId: '$recordId', fields })
    account;

    get revenue() {
        return getFieldValue(this.account.data, REVENUE_FIELD);
    }

    get created() {
        return getFieldValue(this.account.data, CREATED_FIELD);
    }
}

JS-Meta

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>51.0</apiVersion>
    <isExposed>true</isExposed>
    <masterLabel>Wire Get Value</masterLabel>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>
    <targetConfigs>
        <targetConfig targets="lightning__RecordPage">
            <objects>
                <object>Account</object>
            </objects>
        </targetConfig>
    </targetConfigs>
</LightningComponentBundle>

I thought that the @wire decorator would serve that purpose, but it works only for Edit / Inline Edit actions. After updating the value from another place (Apex Anonymous window, another web browser's tab etc.), it doesn't change to the new one.

Is there a way to make it work for every type of record update?

1

If you want more general approach you need to use Change Data Capture. https://developer.salesforce.com/docs/atlas.en-us.change_data_capture.meta/change_data_capture/cdc_intro.htm (in short Platform Events)

You need add Account to Change Data Capture in setup and then subscribe to /data/AccountChangeEvent event with lightning/empApi component https://developer.salesforce.com/docs/component-library/bundle/lightning-emp-api/documentation

UPDATE: without losing context

export default class Component extends LightningElement {
  connectedCallback() {
    subscribe(this.channelName, -1, (response) => {
       //handle response.data.payload
    })
    .then(response => {
      console.log("Successfully subscribed");
    });
  }
}

with losing context

export default class Component extends LightningElement {
  connectedCallback() {
    subscribe(this.channelName, -1, function(response) {
       //handle response.data.payload
    }.bind(this))
    .then(response => {
      console.log("Successfully subscribed");
    });
  }
}
6
  • Hi, thanks for the answer. I try to register to the channelName = '/data/AccountChange', but then I receive the following error in the console: Received error from server: {"clientId":"199fmh3kfzq4vtc1l72gb5w6h7xq","channel":"/meta/subscribe","id":"32","subscription":"/data/AccountChange","error":"400::The channel specified is not valid {/data/AccountChange}","successful":false} Do you know what might be a reson for that? I have added Account (Account) to the selected entities in Change Data Capture Setup. Jun 9 at 8:44
  • Sorry, I wrote incorrectly it should be ChangeEvent suffix) /data/AccountChangeEvent together
    – ytiq
    Jun 9 at 10:24
  • did it work for you?
    – ytiq
    Jun 9 at 14:09
  • Event was captured but I couldn't update fields on the component. It turned out that in the callback method the context of LWC is lost and this didn't work properly. I modified my code respectively to sfdcfox' advice in the showToast from messageCallback function of empApi question and now it works fine. Could you please add this information to your answer? I'll accept it then. Jun 10 at 11:06
  • to be honest don't know why you were losing context because if you use arrow functions (=>) in callback it should work. I'll add 2 examples in the answer
    – ytiq
    Jun 10 at 14:05

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.