Get selected filters to customise hit

We are using Algolia instantsearchjs. We want to be able to customise the appearance of our hits based on what filters have been selected. For example we have a filter for if we have preowned items of a product in stock. We only want to show to our customers text saying we have preowned in stock if they’ve selected the preowned filter. I’ve been unable to work out how to check which filters are selected I’ve explored all of the search client objects in chrome dev tools and can’t see any properties that would expose this. Can someone please advise?

Regards
James

Hi @james6,

Thanks for posting. I think the helper.js library which already comes with the InstantSearch.js library will help you out.

For example, in the searchFunction option of the instantsearch object, you can create a function which takes the helper object as a parameter. Then you can inspect the helper object for filters and conditionally take action as you wish:

searchFunction: function(helper) {
    // check filters
    console.log(helper.state.disjunctiveFacetsRefinements);
    let filters = helper.state.disjunctiveFacetsRefinements;

    if (Object.keys(filters).length === 0) {
      console.log("No filters");
      /// do something
    } else {
      console.log("Yes filters");
      /// do something
    }
    // manually trigger the search
    helper.search();
  },

Live sample:

Hope this helps!

1 Like