Search code examples
reactjstypescriptreact-hooksmobxevent-tracking

Can't get react-tracking to work with Typescript, Function components and React-hooks


i am using react.js with typescript, react-hooks and function components. working on prem, I can't use cloud tracking solutions like google analytics, or new relic. also - due to licensing issues, i can't buy an on-prem tracking server solution - so i must implement my own. i stumbled into react-tracking which writes by default to window.dataLayer[] (for google analytics) but should allow to change it - so i tried the below code. but - it doesn't work for me - handleTracking is not being called - how can i make it work and pass to it some meaningful data (currebtly i'm just passing click-test...) Tnx in advance

import React, { useEffect, useContext, useState }  from 'react';
import { Button } from 'semantic-ui-react';
import { observer } from 'mobx-react-lite';
import track, { useTracking } from 'react-tracking';

const JobDashboard: React.FC = () => {
    const { trackEvent } = useTracking();
    const rootStore = useContext(RootStoreContext); 
    const { trackData} = rootStore.jobStore;

    const handleTracking = (trackingData) => {
        //trackData(trackingData);
        console.log(trackingData)
    }

    return (
    <Grid >
        <Grid.Column width={10}>
        <Button
                onClick={() => {
                    trackEvent({ event: 'click-test', dispatch: data=> {handleTracking(data)} });
                }}
                floated="right"
                content="Track"
                color="blue"
            />
        </Grid.Column>
    </Grid>
);
}

export default track({ page: 'JobDashboard' })(observer(JobDashboard));



Solution

  • import React, { useEffect, useContext, useState }  from 'react';
    import { Button } from 'semantic-ui-react';
    import { observer } from 'mobx-react-lite';
    import track, { useTracking } from 'react-tracking';
    
    JobDashboard: React.FC = (track(
      // app-level tracking data
      { app: "JobDashboard" },
      {
        dispatch: data => {
          console.log(data);
          (window.dataLayer = window.dataLayer || []).push(data);
        }
      }
      return (
        <Grid >
            <Grid.Column width={10}>
            <Button
                    onClick={() => {
                        trackEvent({ event: 'click-test'} 
                    });
                    }}
                    floated="right"
                    content="Track"
                    color="blue"
                />
            </Grid.Column>
        </Grid>
    );
    )(export default observer(JobDashboard));