Lightning Web Components – Why Are LWC Variables Not Defined?

My Lightning Web Component operates as expected, data from the apex class is passed into the js class, and renders correctly in the lightning data table. However, in the @wire function, none of my console.logs show up as anything but undefined or an empty array. Debugging in chrome is the same thing, even as i step through the code all the variables are undefined. constantData was just a tester variable, this.data isnt defined either

import { LightningElement, track, wire} from 'lwc';
import getActiveMaterials from 
'@salesforce/apex/pcMaterialsClass.getActiveMaterials';

const columns = [
removed these for space as they aren't pertinent to the question 
]

export default class PcMaterials extends LightningElement {
@track aidata = [];
@track columns = columns;

@wire(getActiveMaterials)
wiredpcMaterials({error, data}) {
    if(data) {
        this.aidata = data;

        let constantData = this.aidata;

        // eslint-disable-next-line no-console
        console.log(constantData);

    } else if(error) {
    this.error = error;  
    }
 }
}

Best Answer

Added based on comments

You are actually getting data but if you are logging directly, it returns proxy object in which the data will not be accessible directly, so you need to log the stringified data.

@wire(getActiveMaterials)
wiredpcMaterials({ error, data }) {
    if (data) {
        this.aidata = data;
        // eslint-disable-next-line no-console
        console.log('DATA => ', data, JSON.stringify(data));
    } else if (error) {
        this.error = error;
    }
}

Here, although you see Array(0) in data, you will get the array of records in JSON.stringify(data)


OLD ANSWER

When the component is rendered 1st time, all the wired services are registered and returns the object {data:undefined,error:undefined}. This is the reason you will always see them (data or error) as undefined on load of page. However, the service will invoke again when it returns the value (apex method return) to data if success or provide error value if failure.

Related Topic