0

I have a simple wire methods which fetch a list of records. In this method, I'm trying to assign a boolean variable as false based on returned data but seems like the assignment in not happening.

js Code below:

 @track emptyCauseRec;

@wire(getCauseRecords, {reId: '$riskcausedetailrecord'})
    causeRecords(wireResult){
        const { data, error } = wireResult;
        this.wiredCauseData = wireResult;
        if(data){
            this.causerecs = data;
           // this.emptyCauseRec=false;
            console.log('causerecs:::'+JSON.stringify(this.causerecs));
            this.error = undefined;
            //Check cause rec empty
            if(this.causerecs == [] || this.causerecs== null){
            this.emptyCauseRec=true;
        }
        }
        else if (error) {
            this.error = error;
            this.causerecs = undefined;
        }
        
        console.log('emptyCauseRec:::'+this.emptyCauseRec);
    }

this.causerecs == [], but this.emptyCauseRec says undefined.

enter image description here

If I initially assign a value as this.emptyCauseRec=false, it always stays false. Where am I doing mistake?

1 Answer 1

0
//Check cause rec empty
if(this.causerecs == [] || this.causerecs== null){

This condition will never be true, because if(data) checks for null already, and someVar == [] will always be false. See:

let a = [];
let b = [];
if(a == b) {
  console.log('This message will never print');
}

This is because a and b are two instances of an Array, and the == in this case simply asks if the two Arrays are the same instance, which would never be true.

Compare to:

let a = [];
let b = a;
if(a == b) {
  console.log('This will always print');
}

The typical way to check if an Array is empty is to check .length:

this.emptyCauseRec = !data.length;

Here, we'll set emptyCauseRec to false if data.length is not 0, or true if it is 0. Note that the line of code above eliminates the need for an if statement; the emptyCauseRec will be set or reset correctly each time the wire method is called with data.

You must log in to answer this question.

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