Reputation: 139
I have it a buy it now only filter button that filters listings that allow that option. Right now with the for loop in the code below, the app crashes when button is clicked. If I remove the for loop, it doesn't crash. I don't really understand the crashing because I'm looping correctly. Atleast I think I am. Does anyone see an issue with my code? beforeCurrentFilter is supposed to reset the filter prior that button click. I have 3 filters total so if more than one is selected, it should revert I think.
filteredPosts: any[] = [];
posts: any[] = [];
beforeCurrentFilter: any[] = [];
buyItNowFilter() {
if (this.buyItNowStatus) {
this.buyItNowStatus = false;
console.log("ITS TRUE");
return;
}
if (!this.buyItNowStatus) {
console.log("its false");
this.beforeCurrentFilter = this.filteredPosts;
this.buyItNowStatus = true;
for (let i = 0; i < this.posts.length; i++) {
if (this.posts[i].auctionType !== "Not Available") {
console.log("LISTING HERE");
console.log(this.posts[i]);
this.filteredPosts.push(this.posts[i]);
}
}
this.posts = this.filteredPosts;
}
}
Upvotes: 0
Views: 52
Reputation: 9240
You can refactor your code to look like this and it should fix your issue, if you use the Array.filter
method you can eliminate the use of the for loop
buyItNowFilter() {
if (this.buyItNowStatus) {
this.buyItNowStatus = false;
console.log('it\'s true');
return;
} else {
console.log('it\'s false');
this.beforeCurrentFilter = this.filteredPosts;
this.buyItNowStatus = true;
this.filteredPosts = this.posts.filter(x => x.auctionType !== 'Not Available');
this.posts = this.filteredPosts;
}
}
Upvotes: 1