javascriptgoogle-analyticsgoogle-tag-managergoogle-datalayer

trying to datalayer update with set() build-in method but not updating


trying to update a value in my datalayer but I can't get it to work. See code below. This inside a class that has btn click methods. btw.

if (window.google_tag_manager["GTM-XXXXX"].dataLayer.get('ecommerce') !== undefined) {
      console.log('update')
      window.google_tag_manager["GTM-XXXXXX"].dataLayer.set('ecommerce', {
        'productId': `${this.product.id}`, 
        'productName': `${this.product.productName}`
      })
   
    } else {
      console.log('create')
      window.dataLayer.push({ 
        'ecommerce': {
          'productId': `${this.product.id}`, 
          'productName': `${this.product.productName}`
      }});
    }

According to this documentation, it should work. https://javascript.tutorialink.com/how-to-update-a-datalayer-variable/

The values get picked up upon click.


Solution

  • Not sure why you need to update the dataLayer

    You can just push it and it will update automatically if you use Google Tag Manager - DataLayer Variable to get the data.

    Any specific use case or requirement?