In LWC, you can get the record Id of the current record on the lightning record page by using @api decorator and recordId property. The recordId is accessible in the wire methods or a button click handler or custom method.

In Lightning web component lifecycle hooks like connectedCallback() or renderedCallback(), the recordId is not available. It’s available in the property declaration and can be used in other parts of the component.

In the below example, wire method and button click handler is used to access the recordId. Please note wire methods are used to perform only read operations and no DML operations can be done.

import { LightningElement, api, wire } from 'lwc';
import getRecordFromApex from '@salesforce/apex/ApexClass.getRecordFromApex';

export default class DemoLwc extends LightningElement {
    @api recordId;

    @wire(getRecordFromApex, {recordId: '$recordId'})
    record(data, error)
    {
        // this.recordId is accessible here
    }

    handleButtonClick()
    {
        console.log('RecordId from button click '+ this.recordId); // this.recordId is accessible here
    }

    connectedCallback()
    {
        console.log('RecordId from connectedCallback '+ this.recordId); //undefined
    }

    renderedCallback()
    {
        console.log('RecordId from renderedCallback '+ this.recordId); //undefined
    }
}

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *