Sending events insights data from frontend instantSearch.js

Created a custom infinte-Hits widget with infinte scroll. Need to add click event insight, by default view event is triggered , but on passing click event in sendEvent function it is still taking click as view event.
Below is the code for widget:-

const customInfiniteHits = connectInfiniteHits(
  (renderArgs, isFirstRender) => {
    const { hits, showMore, sendEvent , widgetParams } = renderArgs;
    const { container } = widgetParams;
    lastRenderArgs = renderArgs;
    if (isFirstRender) {
      const sentinel = document.createElement('div');
      container.appendChild(document.createElement('ul'));
      container.appendChild(sentinel);
      const observer = new IntersectionObserver(entries => {
        entries.forEach(entry => {

  
          if (entry.isIntersecting && !lastRenderArgs.isLastPage) {
            showMore();
           }
        });
      });
      observer.observe(sentinel);

      return;

    }
    container.querySelector('ul').innerHTML = hits
      .map(
        hit =>
          `<a class="result" href="http://docs.citrix.com/${hit.url}" ${sendEvent('click' , hit , 'Result clicked')}}><li>
            <div class="ais-Hits-item">
              <header class="hit-name">
                ${instantsearch.highlight({ attribute: 'title', hit })}
              </header>
              <p class="hit-description">
                ${hit._snippetResult.content.value}
              </p>
              <p class="product-search-algolia">
                ${hit.prod_description}
              </p>
            </div>
          </li></a>
        `
      )
      .join('');
  }
);

Hello @rishank.verma

If it was React InstantSearch, you could’ve done something like this

However, the way you did with the template is different. What’s happening with your code is to call “sendEvent” function and put the result into the DOM, which is not what you intend to do.

If you are using baked-in components which are hits and infiniteHits, then you could’ve just done

What bindEvent does is to put a data- attribute, and hits widget automatically add event listener and when it’s clicked, it reads the attribute and send events.

Now that you’re using a custom component, we need a bit of workaround.

Here is the example I made for you. It basically stores hits globally and whenever an element is clicked, it gets the matched hit object and calls sendEvent with it.

Let me know how it goes.

2 Likes