Developing personalized JavaScript utilizing live data sources

Trying to implement ecommerce events on our website using GTM has been a bit challenging for me. I have attempted to create a custom value with custom JavaScript, but unfortunately, it keeps showing as undefined.

In the initial stages, I came across a data script embedded in our website:

<script id="__NEXT_DATA__" type="application/json">

Subsequently, I proceeded to write a custom JavaScript code snippet as follows:

function() {
  var productInfo = [{
    'id':window.__NEXT_DATA__.props.pageProps.program.products[0].id,
    'name':window.__NEXT_DATA__.props.pageProps.program.products[0].name,
    'price':window.__NEXT_DATA__.props.pageProps.program.products[0].price,
    'category':'exhibition'
  }];

  return productInfo;
}

Given that our website is built with next.js, I am beginning to wonder if utilizing script data in custom JavaScript is even feasible?

Answer №1

It appears that __NEXT_DATA__ is loaded asynchronously and the issue might be related to how GTM is set up. There could be a race condition where the GTM script executes your custom JavaScript function while Next.js is still loading the data.

To address this, I recommend taking the following steps:

  1. Create a trigger in GTM that listens for a custom event.
  2. Add a Tag in GTM that is triggered by the custom event we just created.
  3. In your Next.js application, dispatch a custom event when the app is ready, preferably using the useEffect hook.
  4. If implemented correctly, your custom JavaScript will only run after the app has finished loading, potentially resolving the race condition.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Extract data from nested JSON and populate a list with corresponding values

<ul> <li><a href="" class="edit">a unique item in the list</a></li> <li><a href="" class="edit">another unique item in the list</a></li> <li><a href="" class="edit">yet another unique ...

A guide to removing functions from the render method

Greetings! Currently, I am in the process of creating a simple webpage that utilizes a map function to display all details to the user. Some fellow developers have advised me to remove my functions from the render method, as it continuously renders unneces ...

Loop through an array to find the average values of different segments within the array

I am currently working with an array structured like this: ["2011-06-16 16:37:20",23.2], ["2011-06-21 16:37:20",35.6], ["2011-06-26 16:37:20",41.8], ["2011-07-01 16:37:20",25], ["2011-07-06 16:37:20",22.8], ["2011-07-11 16:37:20",36.4], ["2011-07-16 16:37 ...

What are the advantages of retrieving a complete category tree, including all categories and sub-categories, versus retrieving only the necessary branches as required?

My query is not centered around terminology accuracy, but rather on the goal of presenting a tiered structure consisting of categories, sub-categories, and sub-subcategories. In total, there are approximately 100 different categories and their respective ...

Utilizing Node.js and Jasmine: Preventing the invocation of a Promise function to avoid executing the actual code results in DEFAULT_TIMEOUT_INTERVAL

There is a function below that returns a promise. public async getAverageHeadCount(queryParams: Params, childNode: any, careerTrackId: string): Promise<Metric> { const queryId = this.hierarchyServiceApiUrl + "rolling-forecast/ahc/" + q ...

Starting a Nextjs application with the NewRelic agent: A step-by-step guide

I recently set up the Newrelic agent for my Nextjs application. Here are the steps I have taken so far: npm install @newrelic/next After installation, I copied the newrelic.js file to the root folder and added my license key and app name to it. Furtherm ...

Disable the monthly navigation feature in the uib-datepicker

Is there a way to disable or remove the month/year navigation button on the Angular uib-datepicker component? We are struggling to find a solution to prevent users from clicking on the "Month/Year" text located between the navigation arrows. You can find m ...

Obtain scope in AngularJS using object ID

Is it possible to retrieve the specific scope of an object by accessing it through an ID? I am currently using angular ui tree for a navigation menu. However, I face an issue where after adding a subitem and saving the navigation into a mysql database, th ...

performing functions concurrently within angularjs

I am currently utilizing angularjs 1.0 within my application. There is a dropdown on my cshtml page <select tabindex="2" id="Employee" ng-model="models.SelectedEmployee" ng-change="changeEmployee()" disabled="disabled" class="Answer" size="6"> < ...

Learn how to automatically set the checked state of a radio button by toggling another radio button

I have two sets of radio buttons, each with four options. The first set has no default selection (unchecked) using jQuery, while the second set has the first option checked by default. What I'm looking to achieve is that when a radio button in the f ...

Having trouble finishing the npm installation process

Having trouble with completing 'npm install'. Can someone please assist me?</p> <pre><code>Encountering a warning about an old lockfile while running npm install. The package-lock.json file was created with an outdated version o ...

Submitting information to an HTML page for processing with a JavaScript function

I am currently working on an HTML page that includes a method operating at set intervals. window.setInterval(updateMake, 2000); function updateMake() { console.log(a); console.log(b); } The variables a and b are global variables on the HTML page. ...

The webpage displays the element as <span class="icon">&#xe80d;</span> instead of rendering it properly

In my ReactJS project, I have created a component called Menu1item: class Menu1item extends React.Component{ render(){ return ( <div> {this.props.glyph}{this.props.value} </div> ) ...

What sets Joomla file inclusion apart from the rest?

Can someone please explain the difference between including a JavaScript script file in the following two ways? I created this within a system plugin in Joomla and included the JavaScript file inside the "onAfterInitialise" function. 1) <script type ...

Javascript Code for toggling the visibility of a panel

I need help with a JavaScript code that can show or hide a panel depending on the data in a grid. If the grid has data, the panel should be displayed, but if the grid is empty, the panel should be hidden. I attempted to use the following code, but it did ...

Generating a list of objects from an array of strings

I am currently facing an issue in my code and I could use some help with it. Below are the details: I have a array of string values containing MAC addresses and constant min & max values. My goal is to map over these MAC values and create an array of obje ...

Problem with routing: Request parameters not being collected

I am currently working on a project to create a wikipedia clone. Initially, I set up an edit route that looks like this: router.get('/edit/:id', function(req, res){ var id = req.params.id; console.log(id); models.Page.findById(id, ...

JavaScript and the Firefox Scratchpad platform

Currently, I am utilizing the MDN guide for learning JavaScript and experimenting with examples using scratchpad. Here's a scenario: console.log('The value of b is ' + b); var b; Why does the console log display "The value of b is -1"? I ...

Issues with the execution of Jquery function

Hey guys, take a look at my code: //Additional Jquery codes // display_popup_crop : revealing the crop popup function display_popup_crop(link) { alert("show_popup_crop function is triggered!"); // changing the photo source $('#cropbox&a ...

Retrieve the response text using native JavaScript

Dealing with the nature of asynchronous XMLHTTPRequest in JavaScript can be tricky. I faced a challenge where I needed to return the responseText value but found it impossible due to this nature. To overcome this, I came up with a workaround by calling a f ...