sendAnalyticsEvent
The
sendAnalyticsEvent
function triggers events in the browser, following the Google Analytics 4 (GA4) data model. This function is primarily used for ecommerce tracking but also supports custom events, serving as a centralized point for managing events.sendAnalyticsEvent
doesn't send events to any analytics provider. To intercept events triggered by this function, use theuseAnalyticsEvent
hook.
Import
_10import { sendAnalyticsEvent } from '@faststore/sdk'
Usage
In the component related to the event, declare a callback function. In this function, define an event object with the desired event type (example:
add_to_cart
) and call sendAnalyticsEvent
. Then, pass the related event as an argument. Finally, call the callback function in the event trigger (example: onClick
).Consider the following example of an
add_to_cart
event triggered by the button
component:
_23import { useCallback } from 'react'_23import { sendAnalyticsEvent } from '@faststore/sdk'_23_23const MyComponent = () => {_23 const addToCartCallback = useCallback(() => {_23 import('@faststore/sdk').then(({ sendAnalyticsEvent }) => {_23 /* ... */_23_23 const addToCartEvent = {_23 name: 'add_to_cart',_23 params: {_23 items: [_23 /* ... */_23 ],_23 },_23 }_23_23 sendAnalyticsEvent(addToCartEvent)_23 })_23 }, [])_23_23 return <button onClick={addToCartCallback}>Add to cart</button>_23}
Check the list of available types.
Exporting custom event types with generics
The
sendAnalyticsEvent
function supports generics, enabling you to extend default types or modify existing ones. This approach provides type-checking and code suggestions for your custom event properties.Consider the following example of providing a custom type reference for
sendAnalyticsEvent
:
_13import { sendAnalyticsEvent } from '@faststore/sdk'_13_13interface CustomEvent {_13 name: 'custom_event'_13 params: {_13 customProperty?: string_13 }_13}_13_13/**_13 * By passing CustomEvent as a generic type to sendAnalyticsEvent, you'll receive code hints for all properties of this type, including params subfields._13 */_13sendAnalyticsEvent<CustomEvent>(/* ... */)