3

i'm using react-ga from track my react app using google analytics. I'm fetching the tracking id through an API call and is returned after approximately 4 seconds. My function is this:

const withTracker = (WrappedComponent, options = {}) => {
  const trackPage = (page) => {
    ReactGA.set({
      page,
      options
    });
    ReactGA.pageview(page);
  };

  class HOC extends Component {
    componentDidMount() {
      ReactGA.initialize(this.props.partnerTrackingCode);
      const page = this.props.location.pathname;
      trackPage(page);
    }

    componentWillReceiveProps(nextProps) {
      console.log(nextProps);
      const currentPage = this.props.location.pathname;
      const nextPage = nextProps.location.pathname;

      if (currentPage !== nextPage) {
        trackPage(nextPage);
      }
    }

    render() {
      return <WrappedComponent {...this.props} />;
    }
  }

  return HOC;
};

export default withTracker;

The problem is that the initiliaze function must be called first and is being called with undefined because at first the trackid is undefined(remember that is fetched asynchronously). I used this edit:

const withTracker = (WrappedComponent, options = {}) => {
      const trackPage = (page) => {
        ReactGA.set({
          page,
          options
        });
        ReactGA.pageview(page);
      };

      class HOC extends Component {
        componentWillReceiveProps(nextProps) {
          if(nextProps.trackId) {
            ReactGA.initiliaze(nextProps.trackId);
            const currentPage = this.props.location.pathname;
            const nextPage = nextProps.location.pathname;
            trackPage(nextPage);
         }
        }

        render() {
          return <WrappedComponent {...this.props} />;
        }
      }

      return HOC;
    };

but i'm getting an error that cannot read property parentNode of undefined Do you have an ideas what to do?

RamAlx
  • 6,976
  • 23
  • 58
  • 106

0 Answers0