[SalesForce] LWC – Cannot read property * of undefined

I'm trying to implement a Google map using LWC, the component is on the record page called Project__c, I want to use Address__c as an input:

import { LightningElement, api, wire } from 'lwc';
import { getRecord } from 'lightning/uiRecordApi';
import ADDRESS_FIELD from '@salesforce/schema/PRoject__c.Address__c';


export default class Map extends LightningElement {
    @api recordId;
    @wire(getRecord, { recordId: '$recordId', fields: [ADDRESS_FIELD] })
    project;

    mapMarkers = [
        {
            location: {
                City: this.project.ADDRESS_FIELD.value,
                State: 'Norway',
            },
        },
    ];
    zoomLevel = 5;
}

When I open the record page I get the following error:

render threw an error in 'c:map' [Cannot read property 'ADDRESS_FIELD'
of undefined]

The Project__c.Address__c is populated, so I'm not sure how to continue.

I tried replacing this.project.ADDRESS_FIELD.value with this.project.ADDRESS_FIELD but got the same results.

Best Answer

I think it is actually a timing issue - getRecord is an async operation, so you need the template to check for it before it renders - this works for me

<template>
    <template if:true={record}>
    <lightning-map
            map-markers={mapMarkers}>
    </lightning-map>
    </template>
</template>

//js controller

import { LightningElement, api, wire, track } from 'lwc';
import { getRecord } from 'lightning/uiRecordApi';
import ADDRESS_FIELD from '@salesforce/schema/Project__c.Address__c';

export default class StackExample extends LightningElement {
@track mapMarkers;
@track zoomLevel;
@track record;

    @api recordId;
    @wire(getRecord, { recordId: '$recordId', fields: [ADDRESS_FIELD] })
    wiredProject({ error, data }) {
        if (data) {
            this.record = data;
            console.log(JSON.stringify(this.record));
            this.mapMarkers = [
               {
                   location: {
                       Street: this.record.fields.Address__c.value,
                       City: 'Washington',
                       State: 'DC',
                   },
               },
           ];
           this.zoomLevel = 5;
            this.error = undefined;
        } else if (error) {
            this.error = error;
            this.record = undefined;
        }
    }
}
Related Topic