Push urls to an array in Lightning Web Component

arrayjavascriptlightning-web-componentsnavigation

Im trying to make an LWC that shows a list of contact tiles that have their own url to navigate to the contact record page. I cannot seem to get the url to push into the array in the .then method. When I console log the urls, I can see them displaying correctly in the console but the URL list is undefined. Any help please would be greatly appreciated!

import { LightningElement, api, wire, track } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';
import { getSObjectValue } from '@salesforce/apex';
import { getRecord, getFieldValue } from 'lightning/uiRecordApi';
import getContacts from '@salesforce/apex/AccountController.getContacts';
import ACCOUNTNAME_FIELD from '@salesforce/schema/Account.Name';
import CONTACTID_FIELD from '@salesforce/schema/Contact.Id';

export default class RelationshipMap extends NavigationMixin(LightningElement) {
@track actions = [
    { label: 'Edit', value: 'edit', iconName: 'utility:edit' },
    { label: 'Delete', value: 'delete', iconName: 'utility:delete' },
];
@api recordId;
urlList;
contacts;
error;

@wire(getRecord, { recordId: '$recordId', fields: [ACCOUNTNAME_FIELD]})
account;

/*
@wire(getContacts, { accId: '$recordId' })
contacts;
*/

@wire(getContacts, { accId: '$recordId' })
contacts({ error, data }){
   if(data){
       this.contacts = data;
       this.error = undefined;
    for(let i in this.contacts){
        this[NavigationMixin.GenerateUrl]({
            type: "standard__recordPage",
            attributes: {
                recordId: getSObjectValue(this.contacts[i], CONTACTID_FIELD),
                objectApiName: "Contact",
                actionName: 'view',
            },
        }).then((url) => {
            console.log(url); 
            this.urlList.push(url);
        });
    }
    console.log("URL List: " + this.urlList);
   } else if(error){
       this.error = error;
       this.contacts = undefined;
       console.log("Error");
   }
}

get accountName() {
   return this.account.data ? getFieldValue(this.account.data, ACCOUNTNAME_FIELD) : '';
}
}

Best Answer

You can use Promise.all to make your code much faster and easier to read:

Promise.all(
  this.contacts.map((contact) =>
    this[NavigationMixin.GenerateUrl]({
      type: "standard__recordPage",
      attributes: {
        recordId: getSObjectValue(contact, CONTACTID_FIELD),
        objectApiName: "Contact",
        actionName: "view",
      },
    })
  )
).then((urls) => (this.urlList = urls));
Related Topic