[SalesForce] LWC: wire and getRecord, get field values

It's crazy. I'm gonna crash the table.
How to show variable {name} ?

Iterated component html:

<template>
    <p>{idx} </p>
</template>

Properly shows:

enter image description here

But When i try to add {name} to html it not works!

js code:

import { LightningElement, api, wire } from 'lwc';
import { getRecord } from 'lightning/uiRecordApi';
const FIELDS = [
    'Trip__c.Name',
    'Trip__c.Trip_Status__c'
];

export default class TripListItem extends LightningElement {
    @api idx; // got from parent component // works and displayed properly!

    @wire(getRecord, { recordId: '$idx', fields: FIELDS }) rec;

    get name() {
        return this.rec.data.fields.Name.value;
    }
}

Best Answer

Provisioning data via @wire is asynchronous. In your template you need to guard against this.rec.data being undefined which is the case until data is provisioned.

<template>
  <template if:true={rec.data}>
    {idx} {name}
  </template>
</template>

In your JavaScript add a getter for name.

import { getRecord, getFieldValue } from 'lightning/uiRecordApi';
...
get name() {
  return getFieldValue(this.rec.data, ‘Trip__c.Name');
}

A functioning example using this pattern is https://github.com/trailheadapps/lwc-recipes/tree/master/force-app/main/default/lwc/wireGetRecordUser

Related Topic