Cannot read property 'trim' in ion-searchbar

#1

Hi everyone
in ionic 3
I am using ion-searchbar to search inside array named offers
everything is good but if I cancel (click on X icon) shows me this error.
ERROR TypeError: Cannot read property 'trim' of undefined
this is my code:

.html
<ion-searchbar platform="ios" (ionInput)="getItems($event)" (ionCancel)="onCancel($event)"></ion-searchbar>

.ts
 getItems(ev: any) {
    const val = ev.target.value;

      if (val.trim() !== '') {
        this.offers = this.offers.filter((item) => {
          return item.title.toLowerCase().indexOf(val.toLowerCase()) > -1 || item.description.toLowerCase().indexOf(val.toLowerCase()) > -1;
        })
    }
  }
  onCancel(ev:any){
    console.log("canceled.",ev)
  }
#2

hello,
maybe if you click x, the searchbar will cleared, witch force ionInput to fire, where maybe .value delivers undefined back, cause that .trim can’t execue, because val is undefined.

Maybe you can check before trim, that val contain nothing unexpected, like undefined.

Maybe a better way is, that you don’t use anything from ev.whatever and get whatever you need from an other way.

Best regards, anna-liebt

1 Like
#3

ahh I see in doc why you used that. Take a look to the if condition.

getItems(ev: any) {
// Reset items back to all of the items
this.initializeItems();

// set val to the value of the searchbar
const val = ev.target.value;

// if the value is an empty string don't filter the items
if (val && val.trim() != '') {
  this.items = this.items.filter((item) => {
    return (item.toLowerCase().indexOf(val.toLowerCase()) > -1);
  })
}

}
}
Best regards, anna-liebt

1 Like