0

I have an @wire service that pulls back from records using apex. I thought that if there were no records returned than the if(result.data) would not run. However, when I open my lwc and there are no records, the console that I am in success is run. This is a problem for me because I am trying to set some other fields on success like the account name. Any help would be greatly appreciated!!!

    @wire(getnotes, {accountId: '$recordId'})
  
notes(result) {
    /* eslint-disable no-unused-vars */
  //if we have data returned
if (result.data) {
    console.log('Im in success and here is the data ' + JSON.stringify(result.data));
            //assign the data to the data variable - used as the source for the main datatable
          this.data = result.data;

          
            //since we have data, update error to undefined
          this.error = undefined;
            //set the numberrecords field w hich displays on the page
          this.numberrecords= this.data.length;
            //set the account name field from first gs in list
          this.AccountName =result.data[0].Account__r.Name;
   
        
} //end of if data
else if (result.error) {
    console.log('Im in fail’);
  this.error = result.error;
  this.data = undefined
}
}
3

In most languages, including JavaScript, there is a distinction between null and empty objects. A null object is one that doesn't exist, while an empty array is an object, it just has no contents. To visualize this, imagine walking into a brand-new house with nothing in it. This is an "empty" house. Now, visualize walking into an empty area of land with no building at all. There is no house, so we'd call it a "null" house.

As long as an array is returned, it's not null, even if there's nothing inside. It still exists. If you're checking to see if there's anything inside, you need to check for both null and empty:

if(result.data && result.data.length) {

Note that a value of 0 (indicating an empty array) won't satisfy the true condition. This is because 0 is a "falsy" value. You can use this to determine if there's any data inside.

  • Awesome! Thanks so much for the detailed description! As always, I really appreciate it!!! – Frank Jul 1 '20 at 20:27

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.