4

This question is similar to Which is preferable and why: onchange or template.querySelector, in that there are several different ways to do the same thing in LWC but it's not always clear as to which is the best practice way.

When using a wire call, one can then get the value of a field like this (both approaches could be encapsulated in a getter):

  @wire(getRecord, {
    recordId: "$recordId",
    fields: [CLOSE_DATE]
  })
  opportunity;

and then in the .js file:

let closeDate = this.opportunity.data.fields.CloseDate.value;

or:

let closeDate = getFieldValue(
  this.opportunity.data,
  CLOSE_DATE
);

It seems that Salesforce aren't strictly advising one way or the other but it seems that the latter is more 'standard' and less prone to breaking (I suppose if one has a custom field and the API changed, then it would need to be changed in multiple places whereas it would just have to be changed once using getFieldValue).

1 Answer 1

5

Consider this code:

get closeDate() {
  return this.opportunity.data.fields.CloseDate.value;
}

This would throw an error because the wired data wouldn't be available on the first render, which would break your component. Contrariwise, you can write:

get closeDate() {
  return getFieldValue(this.opportunity.data, CLOSE_DATE);
}

And it won't throw an error.

Notice how we also get to use the field token without caring about the structure of the field token, and we get to get the value without worrying about the structure of the wired record data.

I would recommend that you use that getFieldValue and getFieldDisplayValue consistently.

3
  • Thanks! Why would the wired data not be available on the first render? The wired method is called when the component loads, no? Your recommendation makes perfect sense to me but I am confused that some Salesforce docs refer to the former approach, like developer.salesforce.com/docs/component-library/documentation/…. Commented Aug 15, 2022 at 17:49
  • 2
    @AndyHitchings That's because there's a documentation bug. I actually explore the wire life cycle in this answer I wrote some time ago, based on actual scientific research I performed to arrive at the conclusion. If you try that code, you'll get an error like "unable to access property 'fields' of undefined", and the entire page will stop rendering.
    – sfdcfox
    Commented Aug 15, 2022 at 18:13
  • 1
    @AndyHitchings Follow up: Salesforce Doc team has gotten this to the correct place for a future update to happen. The page itself does kind of explain that you're not supposed to do this, but the wording is ambiguous. They're going to clean that up for the next release.
    – sfdcfox
    Commented Aug 17, 2022 at 1:17

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .