1

After following along with Build Bear-Tracking app from Trailhead I am trying to use similar features in my own lwc app.

Using a @wire adaptor I load results from an Apex controller, the method that retrieves the data and sets it to items works fine. I'm able to iterate through the list of items on my .html file.

But when I add a hasResults method to my lwc app, I get the following error:

Cannot read property 'length' of undefined

HTML

<template>
    <div class="container">
      <template for:each={items.data} for:item="article">
        <!-- code here goes for iterating over individual items -->
      </template>
      <template if:false={hasResults}>
          <div class="slds-align_absolute-center slds-m-vertical_small">
              No articles found for this user.
          </div>
      </template>

    </div>
</template>

JS

import { LightningElement, api, wire } from 'lwc';
import loadArticles from '@salesforce/apex/ArticlesController.getUserArticles';

export default class List extends LightningElement {
    @api recordId;
    items;

    @wire(loadArticles, {userId: '$recordId'})
    loadItems(result) {
        this.items = result;
    }

    get hasResults() {
        return (this.items.data.length > 0);
    }

}

While I dont have it in the code here, the iteration loop works and is able to output the article lines, when there is no data my hasResults failsafe doesnt work.

1

That's because items and the data are null and you are trying to access a property 'length' of a null value . You can put a check like

if(this.items && this.items.data) {
   return (this.items.data.length > 0)
}
  return false;

If you set items=''; - It means item is null and console.log(typeof items); will return an object. Null is an object. However, if you just declare let items; and console.log(typeof items); will return undefined

So if you set items=''; , your original code should work.

| improve this answer | |
  • 1
    +1 or just return this.items && this.items.data && !!this.items.data.length; – sfdcfox Apr 27 at 20:30
  • So why does it work without this on the trailhead but not in my code? – Deployment Failure Apr 27 at 22:08
  • If you paste the trailhead code, we can look into it. Updated my answer as well – Manish Anand Apr 28 at 4:11

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.