Getting a "TypeError: Cannot read property 'filter' of undefined" when trying to search a list

Issue

HTML

<ion-content fullscreen>
  <!-- Searchbar with a placeholder -->
  <ion-searchbar
    (ionInput)="filterList($event)"
    placeholder="Zoek een locatie"
  ></ion-searchbar>

  <ion-grid>
    <ion-row>
      <!-- locatie cards -->
      <ion-col class="row1" size="11">
        <ion-list lines="none">
          <ion-item *ngFor="let location of locations">
            <ion-card class="locatieCard">
              <ion-item>
                <img
                  class="locatieImg"
                  src="assets/spar_img.jpg"
                  slot="start"
                />
                <ion-grid>
                  <ion-row>
                    <ion-card-subtitle>{{ location.Name }}</ion-card-subtitle>
                  </ion-row>
                  <ion-row>
                    <ion-button
                      size="small"
                      fill="clear"
                      (click)="presentPopover($event, location.Contact)"
                    >
                      Meer info
                    </ion-button>
                  </ion-row>
                </ion-grid>
              </ion-item>
            </ion-card>
          </ion-item>
        </ion-list>
      </ion-col>

      <ion-col class="row2" size="1"> ion col 2 </ion-col>
    </ion-row>
  </ion-grid>
</ion-content>

TS

import { Component, OnInit, Input, ViewChild } from '@angular/core';
import { ToolbarTitleService } from '../Services/toolbar-title.service';
import { IonSearchbar, PopoverController } from '@ionic/angular';
import { PopoverComponent } from '../popover/popover.component';
import { SyncServiceService } from '../Services/sync-service.service';
import { UserService } from '../Services/user.service';
import { first } from 'rxjs/operators';

@Component({
  selector: 'app-locaties',
  templateUrl: './locaties.component.html',
  styleUrls: ['./locaties.component.css'],
})
export class LocatiesComponent implements OnInit {
  public locations: any[];
  user;
  public locationsBackup: any[];

  constructor(
    private toolbarTitle: ToolbarTitleService,
    public popoverController: PopoverController,
    private syncService: SyncServiceService,
    private userService: UserService
  ) {}

  async ngOnInit() {
    this.toolbarTitle.setToolbarTitle('Locaties');
    this.user = await this.userService.getUser();
    // Haalt alle shops van de gebruiker op en zet ze in locations
    this.locations = await this.syncService.getShops(this.user);
    this.locations = await this.initializeItems();
  }

  // Popover
  async presentPopover(ev: any, Contact: any) {
    const popover = await this.popoverController.create({
      component: PopoverComponent,
      componentProps: {
        phones: Contact.Phones[0].Number,
        email: Contact.Email,
        street: Contact.Addresses[0].Street1,
        city: Contact.Addresses[0].City,
      },
      event: ev,
      translucent: true,
    });
    return await popover.present();
  }

  // Search
  async initializeItems(): Promise<any> {
    this.locations = await this.syncService
      .getShops(this.user)
      .valueChanges()
      .pipe(first())
      .toPromise();
    this.locationsBackup = this.locations;
    return this.locations;
  }

  // Filter
  async filterList(evt) {
    this.locations = this.locationsBackup;
    const searchTerm = evt.srcElement.value;

    if (!searchTerm) {
      return;
    }

    this.locations = this.locations.filter((currentLocation) => {
      if (currentLocation.Name && searchTerm) {
        return (
          currentLocation.Name.toLowerCase().indexOf(searchTerm.toLowerCase()) >
          -1
        );
      }
    });
  }
}


I’m trying to filter through a list of stores. I keep getting a "Cannot read property ‘filter’ of undefined" error. I can’t seem to figure out what I’ve got to change to make it work. Locations is basically an array with objects of stores. Anyone got an idea what to do? I know it has to be something to do with the filterList function.

Solution

Until getShops() returns with value, locations are undefined (hence: cannot read property filter of undefined).

You can initialize it to an empty array:

locations = [];

or check against it being undefined in filterList.

Also, initializeItems is never called, therefore the same goes for locationsBackup.

Answered By – mbojko

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published