After Search function/event

I’m looking for a reliable way to find out when a search has finished loading so that I can do some ‘after load’ functions. Things like sending a virtual page view to Analytics, loading/refreshing advertisements, and so on.

I’m currently doing it like so:

search.on('render', function() {
  // Load Ads
  // Tag Manager & Pageview Functions
  // Etc

The issue with this method is that it fires more often than I need. Example:

  • Initial Page Load: fires once (good)
  • Add Type refinement: fires twice (bad!)
  • Add second refinement: fires once (good)
  • Add third refinement: fires two more times (bad!)
  • etc…

What would be the best way to do what I want? Landing on the page should be one page load/view. Going to another page (via pagination), adding a refinement, or doing a new search should count as a single new page, not two additional new pages.

You can use the searchFunction option to listen for the result event on the helper like this:

const search = instantsearch({
  appId: 'latency',
  apiKey: '6be0576ff61c053d5f9a3225e2a90f76',
  indexName: 'instant_search',
  searchFunction: function(helper) {
    search.helper.once('result', function() {

searchFunction is called on every result so make sure to use once() and not on() to attach the event listener a single time.

Let me know if that works for you.

1 Like

Thanks! It seems to be working just as I need it.