Filter Manager
Filter Manager is a helper class that takes care of the state of filters. What filters are currently selected and what should be sent. It can be passed to listFilters() and then the result is automatically applied to the state. Modifier applyFilterWithManager() can base used to apply the current state of filters to query.
Here is an pseudo code example how to use filter manager. First there is initialization and the search:
import {
KlevuFetch,
search, // search query function
listFilters, // list filter modifier
applyFilterWithManager, // apply filters modifier
FilterManager // the manager
} from "@klevu/core"
// first initialize filter manager. You can do it in global scope or your frameworks component initialization.
const manager = new FilterManager()
// This is the function you would be calling to make the search
async function mySearch() {
const result = await KlevuFetch(
search(
"hoodies", // search term
{}, // search parameters
listFilters({
filterManager: manager // pass manager to list filters so that it will be populated by results
}),
applyFilterWithManager(manager) // when requesting filters use managers current state. In first run its empty.
)
)
}Now you have tools to manage filters with FilterManager. To render currently available filters you can use manager.options and manager.sliders. Sliders include numerical values like price.
for (const option of manager.options) {
console.log(option) // you render code
}To toggle between options you can use toggleOption method.
manager.toggleOption(option.key, option.name)Event
This will change the state of option selection in the filter manager. Now you have to just call mySearch() again to fetch results of changed state. You can do this directly by calling the function or listening a Events (analytics)
import { KlevuDomEvents } from "@klevu/core" // Add KlevuDomEvents enumeration to project
// Function to run when filter selection is updated
const handleFilterUpdate = () => {
mySearch()
}
// Attach event listener
document.addEventListener(
KlevuDomEvents.FilterSelectionUpdate,
handleFilterUpdate
)
// Don't forget remove event listener in your component destructor
document.removeEventListener(handleFilterUpdate)Clearing all selections
To clear all or single category option selections you can use clearOptionSelections function.
manager.clearOptionSelections("Size") // To clear all selections in "Size" option
manager.clearOptionSelections() // To clear all selectionsExporting and importing selections from URL
FilterManager has methods to load current state into URL query parameters and a method to load current
manager.toURLParams(); // returns query string. For example o_color=red
manager.readFromURLParams(new URLSearchParams("o_color=red")); // reads parameters from a string