3

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 Answer 1

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.

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

You must log in to answer this question.

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