2019-12-05 08:54:42 +00:00
|
|
|
// @flow
|
|
|
|
import React, { useEffect, useState } from 'react'
|
|
|
|
import GoogleAnalytics from 'react-ga'
|
|
|
|
import { getGoogleAnalyticsTrackingID } from '~/config'
|
|
|
|
import { COOKIES_KEY } from '~/logic/cookies/model/cookie'
|
|
|
|
import type { CookiesProps } from '~/logic/cookies/model/cookie'
|
|
|
|
import type { RouterProps } from '~/routes/safe/store/selectors'
|
|
|
|
import { loadFromCookie } from '~/logic/cookies/utils'
|
|
|
|
|
|
|
|
let analyticsLoaded = false
|
|
|
|
export const loadGoogleAnalytics = () => {
|
|
|
|
if (analyticsLoaded) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
// eslint-disable-next-line no-console
|
|
|
|
console.log('Loading google analytics...')
|
|
|
|
const trackingID = getGoogleAnalyticsTrackingID()
|
|
|
|
if (!trackingID) {
|
|
|
|
console.error('[GoogleAnalytics] - In order to use google analytics you need to add an trackingID')
|
|
|
|
} else {
|
|
|
|
GoogleAnalytics.initialize(trackingID)
|
2019-12-12 08:29:29 +00:00
|
|
|
GoogleAnalytics.set({ anonymizeIp: true })
|
2019-12-05 08:54:42 +00:00
|
|
|
analyticsLoaded = true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export const withTracker = (WrappedComponent, options = {}) => {
|
|
|
|
const [useAnalytics, setUseAnalytics] = useState(false)
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
async function fetchCookiesFromStorage() {
|
|
|
|
const cookiesState: CookiesProps = await loadFromCookie(COOKIES_KEY)
|
|
|
|
if (cookiesState) {
|
|
|
|
const { acceptedAnalytics } = cookiesState
|
|
|
|
setUseAnalytics(acceptedAnalytics)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
fetchCookiesFromStorage()
|
|
|
|
}, [])
|
|
|
|
|
2020-02-17 22:20:43 +00:00
|
|
|
const trackPage = page => {
|
2019-12-05 08:54:42 +00:00
|
|
|
if (!useAnalytics || !analyticsLoaded) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
GoogleAnalytics.set({
|
|
|
|
page,
|
|
|
|
...options,
|
|
|
|
})
|
|
|
|
GoogleAnalytics.pageview(page)
|
|
|
|
}
|
|
|
|
|
|
|
|
const HOC = (props: RouterProps) => {
|
|
|
|
// eslint-disable-next-line react/prop-types
|
|
|
|
const { location } = props
|
|
|
|
useEffect(() => {
|
|
|
|
const page = location.pathname + location.search
|
|
|
|
trackPage(page)
|
|
|
|
}, [location.pathname])
|
|
|
|
return <WrappedComponent {...props} />
|
|
|
|
}
|
|
|
|
|
|
|
|
return HOC
|
|
|
|
}
|