I want to get Account field values (Name and Site) on loading the component so I can later use them as aguments for apex methods. I also want to set a boolean variable to true if a field is not null so i can show or hide some text in the HTML. I used the same code on connectedCallback() and a buttonAction() that is called from a lightning-button tag
Here's the code I'm using
import { LightningElement,api,wire,track} from 'lwc';
import { getRecord, getFieldValue } from 'lightning/uiRecordApi';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';
import NAME_FIELD from '@salesforce/schema/Account.Name';
import SITE_FIELD from '@salesforce/schema/Account.Site';
export default class UpdateInfoAccount extends LightningElement {
@api recordId;
accountObject = ACCOUNT_OBJECT;
accountName='';
@track testIfSiteNull=false;
accountSite='';
@wire(getRecord, { recordId: '$recordId', fields: [NAME_FIELD,SITE_FIELD] })
record;
connectedCallback() {
console.log('TEST 1: '+this.testIfSiteNull)
this.accountName= this.record.data ? getFieldValue(this.record.data, NAME_FIELD) : '';
this.accountSite= this.record.data ? getFieldValue(this.record.data, SITE_FIELD) : '';
this.testIfSiteNull= this.accountSite!=='' && this.accountSite!==null ? true : false;
console.log('init : Name '+this.accountName+' Site '+this.accountSite);
console.log('TEST 2: '+this.testIfSiteNull);
}
buttonAction(){
console.log('TEST 3: '+this.testIfSiteNull);
this.accountName= this.record.data ? getFieldValue(this.record.data, NAME_FIELD) : '';
this.accountSite= this.record.data ? getFieldValue(this.record.data, SITE_FIELD) : '';
this.testIfSiteNull= this.accountSite!=='' && this.accountSite!==null ? true : false;
console.log('Button: Name '+this.accountName+' Site '+this.accountSite);
console.log('TEST 4: '+this.testIfSiteNull);
}
}
Here are the console log results:
TEST 1: false
init : Name Site
TEST 2: false
TEST 3: false
Button: Name Account 1 Site www.example.com
TEST 4: true
Can you explain what happens here, and if there is any way I can solve this?
Best Answer
Based on your comments:
You should be using
renderedCallback()
here instead ofconnectedCallback()
.From documentation for
connectedCallback()
:whereas
renderedCallback()
mentions:Because you want to populate the field after your component has been rendered, using
renderedCallback()
will allow you to achieve so. So your JS function will look as:Note: Because your
record
property is a wired property, so you will be able to accessthis.record.data
in any function only after lifecycle hooks. So if you try to use that in any lifecycle function, you will end up gettingundefined
exception. From documentation: