Autocomplete: display nb of results in the header

I would like to display the number of results in the header part of the results panel.

I found a way to pass the data using setContext , but it is always giving the number of the previous query and I don’t understand why.

Here is the code. Can you tell me what i am doing wrong ?

// starting autocomplete
  const autocompleteUI = autocomplete({
          container: '#search-searchbar',
          placeholder: 'Search...',
          debug: false,
          clearOnSelected: false,
          openOnFocus: false,
          autoFocus: true,
          getSources({ query,state, setContext }) {
              return [
                {
                  sourceId: 'posts',
                  getItems() {
                    return getAlgoliaResults({
                      searchClient,
                      queries: [
                        {
                          indexName: 'my_index',
                          query,
                          params: {
                            hitsPerPage: 5,
                            clickAnalytics: true,
                            snippetEllipsisText: '…',
                          },
                        },
                      ],
                      transformResponse({ results, hits }) {
                        setContext({
                          nbHits: results[0].nbHits,
                          hits: hits.length
                        });
                        return hits;
                      }
                    });
        },
        getItemUrl({ item }) {
          return item.url;
        },

        templates: {
          header({ html }) {
            const hit_counter = state.context.nbHits || 0;
            let current_headline = query ? hit_counter + ' Articles matching "'+ query + '"' : '';
            return html`<span class="aa-SourceHeaderTitle">${current_headline}</span><div class="aa-SourceHeaderLine" />`;
          },
          footer({ html }) {
            return html`<div class="aa-Footer"></div>`;
          },
          item({ item, components, html }) {
             // ...
              },
        },
      },
    ];
  },
})

Hi @alexandre.plennevaux,

You need to make sure you are passing the current state into header() function or your context may not be current at display time:

        templates: {
          header({ html, state }) {
            const hit_counter = state.context.nbHits || 0;
            let current_headline = query ? hit_counter + ' Articles matching "'+ query + '"' : '';
            return html`<span class="aa-SourceHeaderTitle">${current_headline}</span><div class="aa-SourceHeaderLine" />`;
          },

I was able to reproduce your issue in a codesandbox without state. Here is my working version:

Try searching for “echo dot sa”

1 Like

That was it, indeed, thank you very much Chuck! :slight_smile:

1 Like