0

I'm trying to work with Map in LWC. I have three lightning cards(Each card will have unique identifier. for ex: Key from my map) in my component. I wanted to iterate over the map and fetch value based on key and show it on each lightning card. But even before I can use the map in HTML I'm getting below error when my component is rendered.However, map is returning the expected values.

Error during LWC component connect phase: [Cannot read property 'data' of undefined]

Below is my code:

js code

import { LightningElement, wire , track} from 'lwc';
import controllerMEthod from '@salesforce/apex/myController.controllerMEthod';
export default class myCmponentLWC extends LightningElement {
@track mapData=[];

    @wire(controllerMEthod) wrprMap(result) { 
        if (result.data) {
            var conts = result.data;
            for(var key in conts){
                this.mapData.push({value:conts[key], key:key}); 
            }
        }
    }
}

Apex code

public with sharing class myController{
    public static Map<String, wrapperClass> wrprMap = new Map<String, wrapperClass>();

    @AuraEnabled(cacheable=true)
    public static Map<String, wrapperClass> controllerMEthod() {
        for(object1__c obj : [SELECT Id, field2__c ,field3__c,field4__c   FROM object1__c]){
            wrapperClass = new wrapperClass();
            wrpr.string1= obj.field2__c ;
            wrpr.booleanVal = String.valueOf(obj.field3__c);
            wrpr.string2= obj.Id;
            wrpr.string3= obj.field4__c;       
            wrprMap.put(wrpr.string1, wrpr);
        }
        system.debug('wrprMap---------'+wrprMap);
        return wrprMap;        
    }

    public class wrapperClass{
        @AuraEnabled
        public string string1;
        @AuraEnabled
        public Boolean booleanVal{get; set;}
        @AuraEnabled
        public String string2;
        @AuraEnabled
        public String string3;
    }
}
0

The method may not initially return any data before hitting the server, so you should check for that first:

if(result && result.data) {
  this.mapData = Object.entries(result.data).map(([key,value]) => ({key,value}));
}

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.