Auto select facet values on page load

I want to select a particular facet value automatically on page load if the url contains a certain value or based on a variable in my Javascript code.

There is a guide on how to create a rule and autoselect a facet based on the query or the context but I want to autoselect a facet value based on my url or a variable in the Javascript.

I have looked around but cannot find anywhere to do this. I would appreciate any help.

Thanks in advance.

Hi @myanastasia and welcome!

I’m guessing this is the guide you started with: Auto-selected facets | Algolia

I’d say that guide actually gets you 80% of where you need to be – the key piece is the isRefined check within transformItems for the refinementList.

The last 20% is deciding which refinement to select. In your case, rather than retrieving a rule, you’ll just want to parse the current path (using window.location.href or window.location.pathname to extract the value you need. Once you have that, you just select the appropriate value.

For instance, let’s say your facet lives on the second level of your path:
https://mysite.com/category/shoes/

You could do something like this (haven’t tested this):

search.addWidgets([
  refinementList({
    // ...
    transformItems(items) {
      const facetFilters =
        (window.location.pathname.split('/')[1]) ||
        [];
      return items.map((item) => ({
        ...item,
        isRefined:
          item.isRefined ||
          facetFilters.includes(`categories:${item.value.toLocaleLowerCase()}`),
      }));
    },
  }),
]);

Thank you for your response.

This gets me half way there by selecting the facet value on load however the refinement is not applied.

When I implemented this, the facet is selected but the results in hits are not filtered and no refinement is shown in current refinements. How can I also filter the results displayed in infiniteHits and refinement show in current refinements such that the user can choose to clear the refinement and proceed with a broader search.

Thank you for your help.

@myanastasia

transformItems(items) {
items.forEach(function(arrayItem){
if(window.location.pathname.replace(/^/([^/]).$/, ‘$1’)=== “de”){
if(arrayItem.highlighted === “German”){
arrayItem.isRefined= true;
}
}
if(window.location.pathname.replace(/^/([^/]).$/, ‘$1’)=== “fr”){
if(arrayItem.highlighted === “French”){
arrayItem.isRefined= true;
}
}
else{
if(arrayItem.highlighted === “English-US”){
arrayItem.isRefined= true;
}
}
});
return items;
},
by setting the “isRefined” property I am able to preselect my desired field,