Send events to Analytics to track impressions

Hello.
I need to track impression, and send some events to analytics, for every search result received.
I make it using algolia helper, and setting a callback in the on result event, but is not firing the first time the results are loaded.

I make an example, with a console.log, as you can see, the first time is not logging anything, but in every further refinement is working.

There is a better way to do this, or make this work properly?
Thanks

Hi @sassaroli,
Might the analytics InstantSearch component be what you are looking for? The analytics widget pushes the current state of the search to the analytics platform of your choice. It requires the implementation of a function that pushes the data. This example shows integrating with Google Analytics.

Let us know if this doesn’t meet your needs!

Hi, thanks for the reply.
Can you show me how to implement this? Because I’m using vue instant search.
And with this example, only can send a pageview.
And I need to send a impression event, for each hit I get.
I workaround in the codesandbox with a flag (trackFirst), but it doesn’t seem right that way.

Hi @sassaroli, I see what you mean. I think this can help.
I would suggest creating a small tracker widget like this:

<script>
import { createWidgetMixin } from 'vue-instantsearch';
import { connectHits } from 'instantsearch.js/es/connectors';

function debounce(fn, delay) {
  let timerId;
  return function(...args) {
    if (timerId) {
      clearTimeout(timerId);
    }
    timerId = setTimeout(() => {
      fn(...args);
      timerId = null;
    }, delay);
  };
}

const track = debounce(nextHits => {
  const products = nextHits.map(hit => ({ product_id: hit.objectID }));
  // track products viewed
  analytics.track('Product List Viewed', () => ({
    products
  }));

}, 500);

export default {
  name: 'AisTracker',
  watch: {
    'state.hits': (prevHits, nextHits) => {
      track(nextHits);
    }
  },
  mixins: [createWidgetMixin({ connector: connectHits })],
  render() {
    return null;
  }
};
</script>

// use as <AisTracker></AisTracker>
1 Like