4

How to avoid error Cannot read property of undefined using LWC Wired properties but to display two properties? enter image description hereafterRender threw an error in 'c:tryc' [Cannot read property 'x' of undefined]

HTML file of tryc.html

<template>
    x.data {x.data}<br/>
    y.data {y.data}<br/>
    x.data.x {x.data.x}<br/>
    y.data.y {y.data.y}<br/>
</template>

Listing of Tryc.js

import { LightningElement, wire, api } from 'lwc';
import getX from '@salesforce/apex/TryCont.getX'; 
import getY from '@salesforce/apex/TryCont.getY'; 

export default class Tryc extends LightningElement {
    @wire(getX)
    x
    @wire(getY)
    y
}

Apex Controller

public with sharing class TryCont {

    @AuraEnabled(Cacheable=true)
    public static Map<String, Object> getX() {
        return new Map<String, Object>{'x'=>'y'};
    }
    @AuraEnabled(Cacheable=true)
    public static Map<String, Object> getY() {
        return new Map<String, Object>{'y'=>'x'};
    }

}

1 Answer 1

7

To avoid this problems, it is needed to surround the code with <template if:true tag, usually it is clear and obvious when we rely on load of one parameter. However, when the code depends on two parameters, it is needed to add additional property which would track if both properties has been loaded

@api
get loaded() {
    return !!this.x.data && !!this.y.data;
}

Modified template

<template>

    <template if:true={loaded}>
        loaded!<br/>
        x.data {x.data}<br/>
        y.data {y.data}<br/>
        x.data.x {x.data.x}<br/>
        y.data.y {y.data.y}<br/>
    </template>

</template>

And final version of Lightning Javascript Web Module

import { LightningElement, wire, api } from 'lwc';
import getX from '@salesforce/apex/TryCont.getX'; 
import getY from '@salesforce/apex/TryCont.getY'; 

export default class Tryc extends LightningElement {
    @wire(getX)
    x
    @wire(getY)
    y
    @api
    get loaded() {
        return !!this.x.data && !!this.y.data;
    }
}
4
  • Great answer. You shouldn't need the @api on the loaded getter though since that will only be called from the same components template file. Commented Jun 7, 2019 at 17:31
  • I can't make it @ track to rerender the component once value of loaded is changed so I must use @ api
    – Patlatus
    Commented Jun 10, 2019 at 10:50
  • @TrevorBliss so I am afraid that if I remove api decorator, lightning web component will not be rerendered once the value of loaded is changed, so it will hang in the unloaded state or will load immediately if user is lucky
    – Patlatus
    Commented Jun 10, 2019 at 10:53
  • You don’t need @api or @track on getters referenced from the template. Your getter relies on reactive @wire properties. The system understand transitive dependencies. Commented Jul 17, 2019 at 14:48

You must log in to answer this question.

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