For the event tracking, I did something similar at Accordo. So, I would like to share my thoughts about the tracking design at FE:
- Encapsulate an EventTracking class for the common fields and the API call. Pseudocode may like follow:
class EventTracking {
fields = {};
constructor() {
// Init evn related configs and common fields
}
trace = ({ eventType, eventName, fields }) = {
API.post(LOG_ADDRESS, {
eventType,
eventName,
...this.fields,
...fields
})
}
}
export default new EventTracking();
- Use Custom Event to collect events at window root (Based on the events bubble up).
command.addListener(COMMAND_EVENTS.EVENT_TRACK, tracking.track);
- Dispatch an event thru API or auto-collect events at the root node. Dispatch manually
command.dispatch(COMMAND_EVENTS.EVENT_TRACK, { eventType, eventName });
// Moreover, we can encapsulate event methods into an `eventTracking` utils
Auto Collect
// In App.js
// traceClickEvent will dispatch COMMAND_EVENTS.EVENT_TRACK with the eventName
// and optional fields collected from the attribute of `data-track` from
// a specific component.
<div id="root" onClick={eventTracking.trackClickEvent)>
// The specific React component you want to trace
<ViewMore
className={`${eventTracking.TRACK_CLICK_CLS} someOtherClasses`}
data-track={JSON.stringify({ eventName })}
to={PATHS.DEPARTMENT_SPEND}
>
Details Spending
</ViewMore>