Lightning Web Component: recordId unavailable from inside constructor
The following code prints "undefined from constructor" but gets the correct recordId when used by the button click from handleClick(). Would anyone know what I'm missing? Thank you in advance.
import { LightningElement, api } from 'lwc';
export default class Tester extends LightningElement {
@api recordId;
constructor(){
super();
console.log(this.recordId + ' from constructor');
}
handleClick(){
console.log(this.recordId + ' from click handler')
}
}
Solution 1:
The parent properties such as recordId are not passed until after the constructor is called and the component is attached to the dom. See the code below.
For more information about lifecycle methods go here: https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.reference_lifecycle_hooks
import { LightningElement, api } from 'lwc';
export default class Tester extends LightningElement {
@api recordId;
constructor(){
super();
}
connectedCallback(){
console.log(this.recordId + ' from connectedCallback')
}
handleClick(){
console.log(this.recordId + ' from click handler')
}
}