Search code examples
reactjsadobe-analytics

Adding Click Event Listener to Adobe Data Layer in React


I'm just starting to enter the world of Adobe Analytics. I'm working in React with Typescript and I am trying to leverage the adobe data layer to send information to Adobe Launch. I've been able to successfully use the adobe push function (i.e. window.adobeDataLayer.push({ test: 'test succeeded' })) and can both see that in the console via window.adobeDataLayer.getState() and ran a simple test to confirm it made its way to Adobe Launch.

However, when it comes to adding an event listener, I'm stumped. I attempted to follow Adobe's Documentation and came up with the following (doStuff() was just to confirm that eventListeners were working as expected, which they do):

function myHandler(event: any): void {
  console.log("My handler was called")
}

function doStuff() {
  console.log('do stuff was called')
}
function adobeAnalyticsTest(): void {
  console.log(' adobeAnalyticsTest function called')

  window.adobeDataLayer = window.adobeDataLayer || []
  window.adobeDataLayer.push({ test: 'test succeeded' })

  window.addEventListener('click', doStuff)

  window.adobeDataLayer.push(function (dl: any) {
    dl.getState()
    dl.addEventListener('click', myHandler)
  })

}
useEffect(() => {
  adobeAnalyticsTest()
}, [])

Looking at window.adobeDataLayer, I couldn't see anything that seemed to indicate there was a click event listener (although this could be ignorance on my part) nor was 'My Handler was called' ever logged to the console. Does anyone have any ideas as to what I'm doing wrong or know how to tell when it's working correctly?


Solution

  • At face value, it looks like you don't have anything in your code that actually calls adobeAnalyticsTest().

    Also, the listener you attach to dl doesn't listen for DOM events like clicking on something in window (like your window.addEventListener line); it listens for payloads pushed to adobeDataLayer where the passed event property value matches what you are listening for.

    For example, put adobeDataLayer.push({'event':'click'}) in your js console you should see "My handler was called".

    Think of it more like subscribing to a CustomEvent (because that's what it is, under the hood), rather than a native DOM event.