Search bar with List not working

I’ve a virtual scroll list with a search bar using Ionic 2.0.1.
HTML code:
<ion-searchbar (ionInput)=“getItems($event)”>

TS code
getItems(ev: any) {
// Reset items back to all of the items
console.log(“reinitialize”);
this.initializeItems();

// set val to the value of the searchbar
let val = ev.target.value;
console.log("search for: " + val);
// if the value is an empty string don't filter the items
if (val && val.trim() != '') {
  console.log("filtering");
  this.items = this.items.filter((item) => {
    return (item.toLowerCase().indexOf(val.toLowerCase()) > -1);
  })
}

}

When a try to enter a search text I can see the list getting filtered for a split second and then it goes back to the original state to show all the items again.

UPDATE - with some more debugging I can see that the filter is taking effect in the code but not updating in the list!
UPDATE2 - it all works when items is a fixed array. But when I read items from storage it doesn’t work!
What am I doing wrong?

where is ur storage code? u probably not doing a .then on the storage get

Thanks for your reply. My storage code is called from initializeItems().

initializeItems() {
//get items
this.dataService.getItems().then((cItems) => {
if (cItems) {
this.items = JSON.parse(cItems);
}
});
}

where is your storage.get()

It’s been called from:

i was talking about your actual “storage.get” the one that retrieves from storage, show me the implementation of getItems

You are acting as though initializeItems behaves synchronously. You cannot rely on this.items being set to anything until the underlying promise resolves. Return it from initializeItems and chain off that.

initializeItems(): Promise<Item[]> {
  // the data service should be responsible for dealing with JSON and getting data into the proper format. 
  // that should not be client code responsibility
  return this.dataService.getItems();
}

this.initializeItems().then((items) => {
  this.items = items;
  let val = ev.target.value;
  if (val && val.trim() != '') {
    // do filtering
  }
  // only in here can you rely on this.items having been received
});

// outside here you cannot rely on this.items not being stale

Thanks @zoinky and @rapropos for helping. I took a hint from @rapropos and was able to resolve the situation like this.

  getItems(ev: any) {
// Reset items back to all of the items
console.log("reinitialize");

this.dataService.getItems().then((cItems) => {
  if (cItems) {
    this.items = JSON.parse(cItems);

    // set val to the value of the searchbar
    let 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);
      })
    }
  }
});
}
1 Like