Skip to content

Commit

Permalink
✨ Collect analytics accordingly to cookies preferences #1843
Browse files Browse the repository at this point in the history
  • Loading branch information
fernandolucchesi committed Oct 30, 2023
1 parent a50ae84 commit 707782a
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
1 change: 1 addition & 0 deletions web/lib/gtm.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export const pageview = (url) => {
}

export const pushToDataLayer = (event, data) => {
console.log(event, data)
window.dataLayer = window.dataLayer || []
window.dataLayer.push({
event: event,
Expand Down
14 changes: 11 additions & 3 deletions web/lib/hooks/useVideoAnalytics.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { pushToDataLayer } from '../../lib/gtm'
import { useEffect, useMemo, useCallback } from 'react'
import { useEffect, useMemo, useCallback, useState } from 'react'
import useConsentState from './useConsentState'

type GTMTitleType = { videoTitle: string | undefined }
Expand All @@ -9,6 +9,14 @@ const GTM_PLAY_EVENT = 'video_play'
const GTM_PAUSE_EVENT = 'video_pause'

const useVideoAnalytics = (videoRef: VideoRefType, src: string, title?: string): void => {
const [allowAnalytics, setAllowAnalytics] = useState(false)

useConsentState(
'statistics',
() => setAllowAnalytics(true),
() => setAllowAnalytics(false),
)

const GTM_TITLE: GTMTitleType = useMemo(() => ({ videoTitle: title || src }), [title, src])

const handlePlayEvent = useCallback(() => {
Expand All @@ -22,7 +30,7 @@ const useVideoAnalytics = (videoRef: VideoRefType, src: string, title?: string):
useEffect(() => {
const videoElement = videoRef.current

if (!videoElement) return
if (!videoElement || !allowAnalytics) return

videoElement.addEventListener('play', handlePlayEvent)
videoElement.addEventListener('pause', handlePauseEvent)
Expand All @@ -32,7 +40,7 @@ const useVideoAnalytics = (videoRef: VideoRefType, src: string, title?: string):
videoElement.removeEventListener('play', handlePlayEvent)
videoElement.removeEventListener('pause', handlePauseEvent)
}
}, [videoRef, handlePlayEvent, handlePauseEvent])
}, [allowAnalytics, videoRef, handlePlayEvent, handlePauseEvent])
}

export default useVideoAnalytics

0 comments on commit 707782a

Please sign in to comment.