[SalesForce] Read URL parameters in LWC salesforce

I am using lightning navigation to pass recordId from parent component to child component.

On button click i am navigating to child component like below url –

https://XXXXXXXXXX.lightning.force.com/lightning/cmp/c__ChildComp?c__recordId=t2B9E000123JvDJUA0

I need to get the recordId from URL in child component and pass to apex methods.

I tried the below, but not getting the recordId.

  import { LightningElement, api, track, wire } from "lwc";
    import { getRecord, generateRecordInputForUpdate } from "lightning/uiRecordApi";
    import { CurrentPageReference } from "lightning/navigation";

    export default class TestLWC extends LightningElement {
     @track getrecordId;
      @wire(CurrentPageReference)
      currentPageReference;
     setCurrentPageReference(currentPageReference) {
    this.currentPageReference = currentPageReference;
  }
      getrecordId =
        this.currentPageReference && this.currentPageReference.state.c__recordId

    @wire(getData, { getrecordId: "$getrecordId" })

    }

Best Answer

You can get recordId based on below code using CurrentPageReference object. This will return record id from parent object.

You can get recordId based on below code.  

import { CurrentPageReference } from 'lightning/navigation';
import { LightningElement ,wire,track} from 'lwc';
export default class TestLWC {

    @track recordId='';
     @wire(CurrentPageReference)
    currentPageReference; 

    get recordIdFromState(){
        return this.currentPageReference &&
            this.currentPageReference.state.c__recordId; 
    }
    renderedCallback()
    {
      if(this.recordId==='')
      {
          this.recordId=this.recordIdFromState;
          console.log(this.recordId);
          //call apex after this.recordId has value
      }
    }
}
Related Topic