Lightning Web Components – Fix getRecord and getFieldValue Returning Undefined Values

Here is the javascript code of my LWC

import { LightningElement, api, wire, track } from 'lwc';
import { getRecord, getFieldValue } from 'lightning/uiRecordApi';
import getAlertMetadata from '@salesforce/apex/AlertCommonController.getAlertMetadata';

import ALERT_FIELD from '@salesforce/schema/Case.AlerteBis__c';
const fields = [ALERT_FIELD];

export default class AlertCommon extends LightningElement {

  @api recordId;
  @track records;
  @track error;
  idAlert;

  @wire(getRecord, { recordId: '$recordId', fields})
    requete({error, data}){
      if(data){
        console.log('requete.records', JSON.stringify(data)); // Never rendered
      }else if(error){
        console.log('requete error', JSON.stringify(error)); // Never rendered
      }
    }

  @wire(getAlertMetadata, {idAlert: '$idAlert'}) 
  alertRecords({error, data}){
    if(data){
      this.records = data;
      console.log('this.records', JSON.stringify(this.records)); // Never rendered
    }else if(error){
      this.error = error;
      console.log('error', JSON.stringify(this.error)); // Never rendered
    }
  }

  get alertID() {
    console.log('requete.data', JSON.stringify(this.requete.data)); // It's always undefined
    return getFieldValue(this.requete.data, ALERT_FIELD);
  }

  connectedCallback(){
    console.log('alerteID', this.alertID, this.recordId); // they're always undefined
    this.idAlert = this.alertID;
  }
}

Here is the html

<template if:true={records}>
   TEST {alerteID} {recordId}
</template>

And here is the XML:

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="alertCommon">
  <apiVersion>48.0</apiVersion>
  <isExposed>true</isExposed>
  <targets>
    <target>lightning__AppPage</target>
    <target>lightning__RecordPage</target>
    <target>lightning__HomePage</target>
  </targets>
</LightningComponentBundle>

I'm very new in LWC.
Here I tried to display two variables in the html (alertID and recordId). But they're always undefined (see the comments on the JS code). I don't know why. Everything seems correct though.

Please where I'm wrong ?

Best Answer

define a track variable

@track alertdata;

getRecord is as follows:

  @wire(getRecord, { recordId: '$recordId', fields})
    requete({error, data}){
      if(data){
        this.alertdata = data;
      }else if(error){
        console.log('requete error', JSON.stringify(error)); // Never rendered
      }
    }

alertID method is as follows:

 get alertID() {
    console.log(this.alertdata); 
    return getFieldValue(this.alertdata, ALERT_FIELD);
  }
Related Topic