1

I have this code in my aura and I tried it to convert it to LWC.

Aura:

<a href="{!v.urlRecord.Link__c + '?tag=' + v.urlRecord.Tag__c}" target="_blank" class="alert-link">{!v.urlRecord.Link__c + '?tag=' + v.urlRecord.Tag__c}</a>

What I did in LWC is this:

HTML:

<a href={linkGen} target="_blank" class="alert-link">{linkGen}</a>

JS:

connectedCallback() {
    getUrl({communityName:this.communityName}).then(response => {
        this.urlRecord= response;
        this.linkGen= this.urlRecord.Link__c + '?tag=' + this.urlRecord.Tag__c;
        
    });
}

Apex:

public with sharing class GetUrlController {

@AuraEnabled(cacheable=true)
public static Url__c fetchUrlRecord(string communityName) {
    
    Url__c getUrl;
    
    for(Url__c cUrl:[SELECT Id, Link__c, Tag__c, Active__c, Community_To_Alert_On__c, Start_Time__c, End_Time__c  
                           FROM Url__c
                           WHERE Active__c = true and Community_To_Alert_On__c includes (:communityName)
                           ORDER BY LastModifiedDate DESC])
    {
        if(cUrl.Start_Time__c <= System.Now() &&
           cUrl.End_Time__c > System.Now())
        {
            getUrl = cUrl;
            break;
        }
    }
    
    return getUrl;
}

}

But as expected, it didn't work. Anyone knows what wrong in the code. Any help is appreciated. Thanks!

2
  • Please edit the question to include the imperative apex you are calling, so we can see the response structure.
    – Phil W
    Jun 10, 2023 at 9:13
  • Sorry, I forgot the Apex. Done adding it to the question. Jun 10, 2023 at 10:59

1 Answer 1

1

Because you are invoking the getUrl function directly in connectedCallback(), your this context refers to anything declared within this function.

Try this:

connectedCallback(){
  this.callGetUrl(this.communityName);
}

callGetUrl=(communityName)=>{
  getUrl({communityName})
    .then(response => {
      this.urlRecord= response;
      this.linkGen= this.urlRecord.Link__c + '?tag=' + this.urlRecord.Tag__c;
    }
  });
}

You could also make connectedCallback an arrow function to remove it's this context, but it seems cleaner this way.

1
  • 1
    Thanks. I tried what you suggest and it works. Jun 12, 2023 at 0:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .