I’m having trouble with making the code return all items when the “All” option in the category dropdown is chosen.
Working in Wix Studio Editor, CMS, Wix Velo Dev Mode
Site link: https://mgcnlca.wixstudio.com/found-it/lost-items
What I’ve tried so far: Resetting the filter completely if “All” is selected
Here is my code for reference (for the lost-items dynamic page):
// Velo API Reference: https://www.wix.com/velo/reference/api-overview/introduction
import wixData from 'wix-data';
$w.onReady(function () {
$w('#dynamicDataset').onReady(() => {
count();
});
//trigger search
$w('#categoryDropdown, #sortDropdown').onChange(() => {
search();
});
//search bar filter
let debounceTimer;
$w('#searchBar').onKeyPress(() => {
if (debounceTimer) {
clearTimeout(debounceTimer)
debounceTimer = undefined;
}
debounceTimer = setTimeout(async () => {
await search();
}, 200);
})
});
//search filter function
function search() {
//declarations
let filter = wixData.filter();
let sort = wixData.sort();
let searchItem = $w('#searchBar').value;
let category = $w('#categoryDropdown').value;
let hasSearchItem = searchItem.length > 0;
let hasCategory = category.length > 0;
//search bar filter (checks mulitple fields)
if (hasSearchItem) {
let searchFilter = wixData.filter()
.contains('title_fld', searchItem)
.or(wixData.filter().contains('category', searchItem))
filter = filter.and(searchFilter)
}
//category filter
if (hasCategory) {
if (category === "All") {
// Reset filter completely if "All" is selected
filter = wixData.filter();
} else {
filter = filter.and(wixData.filter().contains('category', category));
}
}
//sort filter
switch ($w('#sortDropdown').value) {
case 'New → Old':
sort = sort.descending('dateFound');
break;
case 'Old → New':
sort = sort.ascending('dateFound');
break;
}
//apply filters with dataset
$w('#dynamicDataset').setFilter(filter).then(() => {
$w('#dynamicDataset').setSort(sort).then(count);
});
}
//count item filter
function count() {
let count = $w('#dynamicDataset').getTotalCount();
if (count > 0) {
$w('#countItems').text = `${count} Lost Item${count === 1 ? '' : 's'} Found`;
}
return count;
}