function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
srikanth darbha 11srikanth darbha 11 

I am having trouble in calling apex imperative call in LWC life cycle method.

Hi Guys,

I want to pass recordID from a LWC Component to a apex class in connectedCallback method.,But sommehow i am getting the value as null inside the class, Not able to understand where i am going wrong,
Can anyone please help me out .

export default class AddContacToDl extends LightningElement {
connectedCallback() {
var rcid= this.recordId;
console.log('rcid---beofre----'+rcid);
getSelectedDLDetails({contactIDname:this.rcid})
.then(data => {
console.log('data------'+data);
for(var i=0; i<data.length; i++) {
console.log('id=seleccted' + data[i]);
this.distvalue = [...this.distvalue ,{value:data[i], label: data[i]}];
}
this.error = undefined;
}).catch(error=>{
this.error = error;
this.distvalue = undefined;
})
}

Apex class-

@AuraEnabled
public static List<String> getSelectedDLDetails(String contactIDname)
{
System.debug(LoggingLevel.info,'ID value------'+contactIDname);
Jigar.LakhaniJigar.Lakhani
Hi Srikanth,

Are you using LWC directly in lightning page or you are using aura component and included that LWC in aura component?

If you are directly using LWC - please make sure to use @api decorator and use recordId variable to get record id.
https://developer.salesforce.com/docs/component-library/documentation/lwc/use_record_context

Please let me know if it works.

Thanks & Cheers,
Jigar (pateljb90@gmail.com)
Ravi Dutt SharmaRavi Dutt Sharma
import { LightningElement, api } from 'lwc';
export default class AddContacToDl extends LightningElement {
  
  @api recordId;
  connectedCallback() {
    var rcid= this.recordId;
    console.log('rcid---beofre----'+rcid);
    getSelectedDLDetails({contactIDname:this.rcid})
    .then(data => {
    console.log('data------'+data);
    for(var i=0; i<data.length; i++) {
    console.log('id=seleccted' + data[i]);
    this.distvalue = [...this.distvalue ,{value:data[i], label: data[i]}];
    }
    this.error = undefined;
    }).catch(error=>{
    this.error = error;
    this.distvalue = undefined;
  })
}

The recordId is set only when you place or invoke the component in an explicit record context. In all other cases, the recordId isn’t set.