Search code examples
algolia

setting initial facet/refinement values when using instantsearch.js


I'm using instantsearch.js and a combination of widgets to display my search results (pretty much modeled exactly after the demos).

I need to set some initial values for facets so certain items are filtered on by default. How do I do this? I know the AlgoliaSearchHelper (helper) object has a method toggleRefinement that should allow me to do this but I can't seem to access this helper prior to calling search.start() which does the initial query.

Any advice or insight on how to set some default refinements would be appreciated. Thanks.

Update: This isn't a duplicate - my issue seems to have been with the instantsearch.widget.toggle. It looks like this widget sets default values behind the scenes before the initial search. I've adjusted my code to not use this widget and to just set the searchParameters.tagFilters property instead. It was the toggle widget throwing things off for me as I couldn't figure out how to override its default filtering.


Solution

  • The easiest way to add initial filters to your instantsearch.js instance is to use an extra custom widget:

      var search = instantsearch({
        appId: 'YourApplicationID',
        apiKey: 'YourSearchOnlyAPIKey',
        indexName: 'YourIndexName'
      });
    
      search.addWidget(
        instantsearch.widgets.searchBox({
          container: '#search-box',
          placeholder: 'Search for FIXME...'
        })
      );
    
      search.addWidget(
        instantsearch.widgets.hits({
          container: '#hits-container',
          templates: {
            item: 'Hit {{objectID}}: FIXME'
          }
        })
      );
    
      // setup initial filters
      search.addWidget({
        init: function(options) {
           // use options.helper (https://github.com/algolia/algoliasearch-helper-js) to initialize the search with custom filters & parameters
           options.helper.addFacetRefinement('MyFacet', 'my value');
        }
      });
    
      search.start();