0

I have a lightning component that may or may not accept query parameters.

In the connected callback, I am trying to grab parameters from currentPageReference and if there are query params then I perform some operation.

@wire(CurrentPageReference )
  currentPageReference ;

    connectedCallback(){
        if(this.currentPageReference && this.currentPageReference.state.c__randomdata) {
                performAPICallouts();
          }
    
      }

My understanding is that the connected callback executes only once. Can I be certain that the currentPageReference will receive data before connectedCallback Lifecycle hook executes?

Or Can the connectedCallback execute before param is loaded in currentPageReference.

This blog shows the above approach. https://www.infallibletechie.com/2020/05/lightning-record-form-lwc-in-salesforce.html

Any good suggestion or solution on solving this ?

3

The connectedCallback will likely be called before the wires are invoked. Instead hang the behaviour that requires some data off where that data becomes available, so in this case when the page reference is returned:

// A private property for holding the full detail of the page reference
_currentPageReference;

@wire(CurrentPageReference)
receivePageReference(result) {
    // Store the response for later use, as needed
    this._currentPageReference = result;

    // Now you can perform your logic
    if (this._currentPageReference.state.c__randomdata) {
        performAPICallouts();
    }
}

That said, this specific wire won't actually perform a server round trip since the data is already available in the client. As such the specific initialization sequence may mean it happens to work doing it the way you suggested - this isn't, however, a good idea in general since wires run asynchronously during the component initialization (or when their reactive parameters are set with a non-undefined value) and often include some form of server round trip.

Thus the best approach is to always process data when you know it has been received.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.