1

I am creating a simple component that retrieves multiple URL and Description fields in a record (e.g. url1__c, desc1__c, url2__c etc) and transforming it into an Array of object in a JavaScript variable so that I can display it as an clickable Avatar with description.

I am already able to query the record via calling an apex (because the object is not supported by the UI Reference API) using the @wire call. In the wire adapter function, I want to process the data so that I can compute the icon. I'm unable to call any function inside though. Any advise? Sample code as follows:

NOTE: I know I can do the same transformation in Apex but want to do it in JavaScript for specific design purposes.

@wire(getContent, { recordId: '$recordId' })
wiredContent({ error, data }) {
    if (error) {
        console.log(error);
    } else if (data) {
        this.contents = new Array()
        for(var x=0;x<data.length;x++){
            if(data[x].URL1__c!=null){
                iconType = getIconType(data[x].URL1__C);
                this.contents.push({
                    key : 'URL1__c',
                    iconType : iconType,
                    docURL : data[x].URL1__C,
                    docDesc : data[x].Desc1__c
                });
            }
            // additional if-condition here
    }
}

getIconType(docUrl){
    var ext = docUrl.substr(docUrl.length,3);
    if(ext.toLowerCase()==="pdf"){
        return "doctype:pdf";
    }
    // additional if-condition here
}
  • 1
    Woops. I figure it out. I can call the function by adding the "this." keyword when calling it from the wiredContent(). – Nino Bustillos Apr 17 at 3:35
  • might as well add it as an answer – glls Apr 17 at 4:08
1

As you noted in your own answer, your code is missing this on the function call. It’s required because getIconType is a class method. You can learn more about JavaScript classes at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes

As for your code sample, it can be greatly simplified by using modern JavaScript array functions.

@wire(getContent, { recordId: '$recordId' })
wiredContent({ error, data }) {
   if (error) {
       console.log(error);
   } else if (data) {
       this.contents = data
           .filter(d => d.URL1__c != null)
           .map(d => {
               return {
                   key: 'URL1__c',
                   iconType: this.getIconType(d.URL1__c),
                   docURL: d.URL1__c,
                   docDesc: d.Desc1__c
               };
           });
   }
}

getIconType(docUrl){
   if (docUrl.endsWith('pdf')) { 
       return "doctype:pdf";
   }
   // additional if-condition here
}
0

Woops. I figure it out. I can call the function by adding the "this." keyword when calling it from the wiredContent().

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.