Instantsearch.js stats widget

This is my current configuration, which works well:

  instantsearch.widgets.stats({
    container: '#stats',
    templates: {
      text: `
        {{#hasManyResults}}{{nbHits}} products found{{/hasManyResults}}
        {{#hasOneResult}}1 product found{{/hasOneResult}}
        {{#hasNoResults}}0 products found{{/hasNoResults}}
      `
    }
  })

What I’d like to do is show a different text before any search is done by the user, so it would look something like this using pseudo code:

Text that is shown before a search is performed:

  • {{#nbHits}}{{nbHits}} products{{/nbHits}}

When a search is performed:

- {{#hasManyResults}}{{nbHits}} products found{{/hasManyResults}}
- {{#hasOneResult}}1 product found{{/hasOneResult}}
- {{#hasNoResults}}0 products found{{/hasNoResults}}

Is this possible? Thank you.

Hi @utxoutput, you can customize the hits widget to add something before the search, however, you will need perform a search request to get the nbHits on an empty query if you want to know how many hits are in that query.

1 Like

Thank you.

Any chance you can share an example of how to do this?

@utxoutput If by search you mean that if nothing is entered in the search box, you can use the query parameter to control what you want to display in stats. You will have to create a custom widget like this. stats | InstantSearch.js | API parameters | API Reference | Algolia Documentation

It can be a little tricky if the definition of search is different for you, for example, if you consider a search is made when someone selects the filter. In this case, the query parameter won’t be helpful and you might have to use some jquery to figure out if there were any filters applied.
You could use isFirstRender as well (check the full example link I gave above)

2 Likes

I found this useful topic, it’s exactly what I needed. :blush: Thanks for this discussion!